Login and Register User — Django Rest Framework

Build a Product Review Backend with DRF — Part 8

Emre Cevik
Python | Django & Rest

--

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

python manage.py startapp auth

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.

email = serializers.EmailField(
required=True,
validators=[UniqueValidator(queryset=User.objects.all())]
)

password = serializers.CharField(write_only=True, required=True, validators=[validate_password])
password2 = serializers.CharField(write_only=True, required=True)

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.

fields = ('username', 'password', 'password2', 'email', 'first_name', 'last_name')

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


extra_kwargs = {
'first_name': {'required': True},
'last_name': {'required': True}
}

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

def validate(self, attrs):
if attrs['password'] != attrs['password2']:
raise serializers.ValidationError({"password": "Password fields didn't match."})

return attrs

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

def create(self, validated_data):
user = User.objects.create(
username=validated_data['username'],
email=validated_data['email'],
first_name=validated_data['first_name'],
last_name=validated_data['last_name']
)

user.set_password(validated_data['password'])
user.save()

return user

or we can user create_user method

def create(self, validated_data):
user = User.objects.create_user(validated_data['username'], validated_data['email'], validated_data['password'])
# At this point, user is a User object that has already been
# saved to the database. You can continue to change its
# attributes if you want to change other fields.

user.first_name = validated_data['first_name']
user.last_name = validated_data['last_name']
user.save()
return user

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!

--

--