Django TypeError字段“ id”需要一个数字,但得到了<class'account.models.User'>

时间:2020-09-22 17:42:22

标签: python django object

错误:TypeError: Field 'id' expected a number but got <class 'account.models.User'>.

我一直在阅读身份验证文档,并且不断收到该错误。我已经尝试过对此进行一些不同的排列,但是我真的不确定到底是什么类型错误,但出了什么问题。

最终目标是只返回新创建的用户的“ id”和“电子邮件”以及令牌,由于这个错误,我还无法测试返回的令牌,但是我想应该很好。

虽然有效,但它正在成功地将新用户发布到数据库中,该用户在另一个具有匹配键的表中具有令牌,现在仅通过测试和弄乱就拥有大约50个用户。

旁注,我已经覆盖了默认的Django Django用户设置,但是我遵循了文档,因此代码应该是可靠的,但是如果需要的话,我可以张贴它

Views.py

from rest_framework import status
from .models import User
from .serializers import UserSerializer, RegisterSerializer
from rest_framework.response import Response
from rest_framework.decorators import api_view
from rest_framework.authtoken.models import Token



@api_view(['POST',])
def RegisterAPI(request):
    if request.method == 'POST':
        serializer = RegisterSerializer(data = request.data)
    if serializer.is_valid(raise_exception=True):
        user = serializer.save()
        content = {
            'user': {'id': user.pk, 'email': user.email},
            'auth': Token.objects.get(user = User).key 
        }
        # Return the reponse
        return Response(content)`

Serializers.py

from rest_framework import serializers
from django.contrib.auth import get_user_model
from django.contrib.auth import authenticate
from .models import User

# Register Serializer
class RegisterSerializer(serializers.ModelSerializer):
    class Meta: 
        model = User
        fields = ('id', 'email', 'password')
        extra_kwargs = {'password':{'write_only': True}}

    def save(self):
        user = User(
            email = self.validated_data['email'],
        )
        password = self.validated_data['password']

        user.set_password(password)
        user.save()
        return user

# User Serializer
class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('email')

Documentation

Similar article that didn't help me

1 个答案:

答案 0 :(得分:1)

您正在将 User模型类传递给 .get(...) 方法,但是它应该是 {{ 1}}模型实例 ,它只是从序列化程序中获得的。

User