Django Rest Framework - 注册后返回用户ID和令牌 [英] Django Rest Framework - return user id and token after registration

查看:565
本文介绍了Django Rest Framework - 注册后返回用户ID和令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

我收到错误

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

我做错了什么?

推荐答案

错误是在行



The mistake is in the line

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

首先,您的用户用户的字段c>模型。其次,您不需要在 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.

如果你只想要 id ,你可以使用 serializer.instance.id

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

这篇关于Django Rest Framework - 注册后返回用户ID和令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆