Login and Register User — Django Rest Framework

Build a Product Review Backend with DRF — Part 8

Emre Cevik
Python | Django & Rest
3 min readOct 23, 2020

--

We recently wrote an article about JWT Authentication. Now we can create new app for user management. For creating new app run startapp command.

Actually, we have created endpoints for login before. At this stage we will move them to the auth application.For this;

Create auth/serializers.py move MyTokenObtainPairSerializer from reviews/serializers.py.

Move MyObtainTokenPairView to auth/views.py from reviews/serializers.py.

Open medium/urls.py and change code with:

Open auth/urls.py and type the following lines of code:

Login endpoint is ready. we should send a POST request to API for checking login endpoint.

As you can see in the picture above the login works very well and the access token is returning.

Now, we can crate a registration form. We want our registered users to have a username, email, username, lastname and password. Let’s define a RegisterSerializer.

If we inherit our RegisterSerializer from a ModelSerializer, it automatically generates validators for the serializer based on the model.

Open auth/serializers.py and type the following lines of code:

Let’s explain this code. We can create new atributes for changing model validations.

We are stating that;

  • the type of email attribute is an EmailField and that it is required and should be unique amongst all User objects in our database.
  • the type of password attribute is an CharField and that it is write only, required and should be a valid password.
  • the type of password2 attribute is an CharField and that it is write only, and required.

These are the fields that our registration form is contains.

We can add extra validations with extra_kwargs option. We set first_name and last_name required.

Password fields must be same. We can validate these fields with serializers validate(self, attrs) method:

When send POST request to register endpoint, it calls RegisterSerializer’s create method which saves user object.

or we can user create_user method

We’re ready to create the view. Open auth/views.py and create a RegisterView with a post action. CreateAPIView used for create-only endpoints.

Open auth/urls.py and add register endpoint:

we should send a POST request to API for checking register endpoint. You must add username, password, password2, email, first_name, last_name to body. If fields passed validations, new user detail will be returning.

When you check users in admin site, you can see the newuser in the list.

You can download part 8 files from

If you want to learn more about Django, do check out the documentation, django rest framework website and make sure to check out parts of this series!

--

--