Django Rest Framework - 注册后返回用户ID和令牌

时间:2016-06-04 10:53:01

标签: django django-rest-framework

我尝试注册用户并返回令牌和用户ID。像这样做

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)

我收到错误

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

我做错了什么?

2 个答案:

答案 0 :(得分:5)

错误在于

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

首先,user模型上没有名为User的字段。其次,您不需要在User模型上过滤以获取创建的用户,因为您已在serializer.instance中拥有该用户。所以,没有必要这条线。

如果您只想要id,可以使用serializer.instance.id获取。

答案 1 :(得分:0)

更整洁的解决方案取决于super()的实现:

    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

并确保"id"包含在序列化程序的字段中:

class UserSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ["id", ...