How to create/register user account with Django Rest Framework API

My solution for account registration with DRF.

Published: June 4, 2020
App Store

Recently I needed a way to let user register to my Django site via API because I was building backend for mobile app but could not find many resources dedicated to this.

So I decided to write a short how-to for other and for myself so I have reference for later 🙂

The first step is to create UserSerializer like so:

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('username', 'password')
        extra_kwargs = {'password': {'write_only': True}}

    def create(self, validated_data):
        password = validated_data.pop('password')
        user = User(**validated_data)
        user.set_password(password)
        user.save()
        return user

The Meta class specifies that we are interested in username and password in this case and the password field is marked as write only so it won’t be part of response.

Next we can move to views.py and create view for registration:

class UserCreate(generics.CreateAPIView):
    queryset = User.objects.all()
    serializer_class = UsersSerializer
    permission_classes = (AllowAny, )

Just like other Django Rest Framework views se specify the queryset, serializer and set permissions.

The last piece of the puzzle is to configure URL path for registration:

urlpatterns = [
..
    path('account/register', views.UserCreate.as_view())
..
]

That is basic user registration via API done. If you are building API for mobile app, I would recommend setting up Token Authentification. This is pretty nice tutorial from SimpleIsBetterThanComplex.

Bluesky logo

Follow on Bluesky to not miss new posts

Filip Němeček profile photo

WRITTEN BY

Filip Němeček Mastodon

iOS blogger and developer with interest in Python/Django.

iOS blogger and developer with interest in Python/Django.