Make jwt token on registration with drf
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
serializers.py
:
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()
try:
validators.validate_password(password=password)
# 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(
username=validated_data['username'],
email=validated_data['email']
)
user.set_password(validated_data['password'])
user.save()
return user
class Meta:
model = UserModel
fields = ('username', 'email', 'password', 'token')
views.py
:
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 = [
permissions.AllowAny
]
serializer_class = UserSerializer