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

nemecek_f

Filip Němeček

Posted on March 24, 2020

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

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
Enter fullscreen mode Exit fullscreen mode

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, )
Enter fullscreen mode Exit fullscreen mode

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())
..
]
Enter fullscreen mode Exit fullscreen mode

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.

💖 💪 🙅 🚩
nemecek_f
Filip Němeček

Posted on March 24, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

What was your win this week?
weeklyretro What was your win this week?

November 29, 2024

Where GitOps Meets ClickOps
devops Where GitOps Meets ClickOps

November 29, 2024