Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework - return user id and token after registration

I try to register user and return token and user id. Doing it like this

from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.authtoken.models import Token
from rest_framework import status
from django.contrib.auth import get_user_model

User = get_user_model()

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

    def create(self, request, *args, **kwargs):
        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)
        user = User.objects.filter(user=serializer.instance)
        return Response({'token': token.key, 'id':user.id}, status=status.HTTP_201_CREATED, headers=headers)

And I get an error

Cannot resolve keyword "user" into field. Choices are: auth_token, date_joined, email, first_name, groups, id, is_active, is_staff, is_superuser, last_login, last_name, logentry, password, user_permissions, username

What am I doing wrong ?

like image 431
Alexey K Avatar asked Jun 04 '16 10:06

Alexey K


2 Answers

A neater solution is to depend on super()'s implementation:

    def create(self, request, *args, **kwargs):
        response = super().create(request, *args, **kwargs)
        token, created = Token.objects.get_or_create(user_id=response.data["id"])
        response.data["token"] = str(token)
        return response

And ensure "id" is included in your Serializer's fields:

class UserSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ["id", ...
like image 52
Chrisjan Avatar answered Oct 19 '22 03:10

Chrisjan


The mistake is in the line

user = User.objects.filter(user=serializer.instance)

Firstly, there is no field named user on your User model. Secondly, you don't need to filter on the User model to get the created user as you already have the user with you in serializer.instance. So, there is no need for that line.

If you just want the id, you can get that using serializer.instance.id.

like image 27
Rahul Gupta Avatar answered Oct 19 '22 04:10

Rahul Gupta