Django Rest Framework - return user id and token a

2019-04-22 06:01发布

问题:

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 ?

回答1:

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.