Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework - return auth token after registration

I want to return an auth token in json after successful user registration. How can I do this ?

For registration I use the following

seriazilers.py

class UserSerializer(ModelSerializer):
    class Meta:
        model = User
        fields = [
            'id',
            'username',
            'password',
            'email',
            ]
        write_only_fields = ('password',)
        read_only_fields = ('id',)

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

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

        return user

views.py

class CreateUser(CreateAPIView):
    queryset = Profile.objects.all()
    serializer_class = UserSerializer
like image 473
Alexey K Avatar asked Jun 03 '16 20:06

Alexey K


2 Answers

The are many ways to do this. Here is example in context of your existing code. (put this in your views.py)

from rest_framework.response import Response
from rest_framework.authtoken.models import Token
from rest_framework import status

class CreateUser(CreateAPIView):
    queryset = Profile.objects.all()
    serializer_class = UserSerializer

    def create(self, request, *args, **kwargs): # <- here i forgot self
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        token, created = Token.objects.get_or_create(user=serializer.instance)
        return Response({'token': token.key}, status=status.HTTP_201_CREATED, headers=headers)
like image 53
Sardorbek Imomaliev Avatar answered Nov 14 '22 13:11

Sardorbek Imomaliev


Here's a simple solution for the user when he/she wants to login/sign-in

first of all download django-rest-framework-jwt with pip

pip install djangorestframework-jwt

in your UserSerializer add this to make sure the username and password are correct (add as many fields as you wish)

username = serializers.CharField(read_only=True)
password = serializers.CharField(read_only=True)

Now in your view.py add this

# authenticate: will check if the user exist
from django.contrib.auth import authenticate
# api_settings: will help generating the token
from rest_framework_jwt.settings import api_settings

def login_page(request):
    payload_handler = api_settings.JWT_PAYLOAD_HANDLER
    encode_handler = api_settings.JWT_ENCODE_HANDLER
    serializer = UserSerializer(data=request.data)

    if serializer.is_valid():
        user = authenticate(username=request.data['username'], password=request.data['password'])
        if user:
            payload = payload_handler(user)
            token = encode_handler(payload)

            return Response({'token': token})

And mainly that's it! hope it helps!

like image 41
Khaled Al-Ansari Avatar answered Nov 14 '22 11:11

Khaled Al-Ansari