Make jwt token on registration with drf

Today, 25th June 2022, Ukraine is still bravely fighting for democratic values, human rights and peace in whole world. Russians ruthlessly kill all civilians in Ukraine including childs and destroy their cities. We are uniting against Putinโ€™s invasion and violence, in support of the people in Ukraine. You can help by donating to Ukrainian's army.

To create custom field in ModelSerializer we will use SerializerMethodField. After declaring token field of that type we need declare get_token method. It accepts User as input and then returns token generated by djangorestframework-jwt.

Also example shows password validation that can be fine-tuned in AUTH_PASSWORD_VALIDATORS setting, starting from Django 1.9

import django.contrib.auth.password_validation as validators
from django.contrib.auth import get_user_model
from django.core import exceptions
from rest_framework import serializers
from rest_framework_jwt.settings import api_settings

UserModel = get_user_model()

class UserSerializer(serializers.ModelSerializer):

    password = serializers.CharField(write_only=True)
    token = serializers.SerializerMethodField()

    def get_token(self, obj):
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(obj)
        token = jwt_encode_handler(payload)
        return token

    def validate(self, data):
        password = data.get('password')
        errors = dict()

        # the exception raised here is different than serializers.ValidationError
        except exceptions.ValidationError as e:
            errors['password'] = list(e.messages)

        if errors:
            raise serializers.ValidationError(errors)

        return super(UserSerializer, self).validate(data)

    def create(self, validated_data):

        user = UserModel.objects.create(

        return user

    class Meta:
        model = UserModel
        fields = ('username', 'email', 'password', 'token')

from django.contrib.auth import get_user_model
from rest_framework import permissions
from rest_framework.generics import CreateAPIView

from main.serializers import UserSerializer

class CreateUserView(CreateAPIView):

    model = get_user_model()
    permission_classes = [
    serializer_class = UserSerializer
#django #djangorestframework
Ivan Borshchov profile picture
Apr 02, 2017
by Ivan Borshchov
Did it help you?
Yes !

Best related