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

nemecek_f profile image Filip Němeček Updated on ・1 min read

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)
        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.

Posted on Mar 24 by:

nemecek_f profile

Filip Němeček


Primarily iOS developer, I also like Django and Python. And dabble with JavaScript occasionally. Love reading and coffee.


markdown guide