覆盖jwt_response_payload_handler来发回序列化用户时出错

时间:2019-11-13 14:24:50

标签: python django django-rest-framework django-rest-framework-jwt

我已向UserSerializer添加了通话 这是我的序列化器

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model=user
        fields="__all__"

我的自定义模型

from django.db import models

class user(models.Model):
    username=models.CharField(max_length=150)
    firstname=models.CharField(max_length=20)
    lastname=models.CharField(max_length=20)
    email=models.CharField(max_length=40)
    password=models.CharField(max_length=40)
    type=models.CharField(max_length=10)

    def __str__(self):
        return self.firstname

我添加了一个自定义JWT处理程序

from login.serializers import UserSerializer


def my_jwt_response_handler(token, user=None, request=None):
   return {
        'token': token,
        'user': UserSerializer(user, context={'request':request}).data
    }

settings.py 中,我有

JWT_AUTH = {
    'JWT_RESPONSE_PAYLOAD_HANDLER': 'login.utils.my_jwt_response_handler'
}

当我尝试登录时,出现此错误吗?

AttributeError: Got AttributeError when attempting to get a value for field `firstname` on serializer `UserSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `User` instance.
Original exception text was: 'User' object has no attribute 'firstname'.

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

您已经迁移数据库了吗? python manage.py makemigrationspython manage.py migrate

我还建议您看一下该博客文章,该文章显示了如何在Django中使用自定义用户模型。

https://wsvincent.com/django-custom-user-model-tutorial/