获取 "AuthToken.user" 必须是 "User" 实例。在 django-rest-knox 中

Getting "AuthToken.user" must be a "User" instance. in django-rest-knox

我正在使用 Django-rest-Knox 创建登录方法。我使用 AbstractBaseUser.

在应用程序中创建了一个自定义用户

这是我的views.py

class LoginView(GenericAPIView):
    serializer_class = LoginSerializer

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)  # Load request body to serializer
        serializer.is_valid(raise_exception=True)  # Validate data in serializer and raise an error if one is found

        user = serializer.validated_data  # Get the validated data from the serializer
        token = AuthToken.objects.create(user)[1]  # Create an Authentication Token for the user

        return Response({
            "user": UserSerializer(user, context=self.get_serializer_context()).data,  # Get serialized User data
            "token": token
        })

Serializer.py

class LoginSerializer(serializers.Serializer):
    username = serializers.CharField()
    password = serializers.CharField()

    # class Meta:
    #     model = User
    #     fields = ('username', 'password')
    def Validate(self, data):
        user = authenticate(**data)
        if user:
            return user
        raise serializers.ValidationError("Incorrect Credentials")

这是我的自定义用户模型

class User(AbstractBaseUser):
    _id = models.AutoField
    email = models.EmailField(verbose_name='email', max_length=255, unique=True)
    username = models.CharField(verbose_name='username', max_length = 100, unique=True)
    name = models.CharField(max_length = 100)
    date_joined = models.DateTimeField(verbose_name="date-joined", auto_now_add=True)
    last_login = models.DateTimeField(verbose_name="last-login", auto_now=True)
    category = models.CharField(max_length=50, default= "teacher")
    is_admin = models.BooleanField(default=False)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    is_teacher = models.BooleanField(default=False)
    is_parent = models.BooleanField(default=False)

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email',]

    objects = UserManager()
    
    def __str__(self):
        # return self.email
        return self.username

    def has_perm(self, perm, obj=None):
        return self.is_admin

    def has_module_perms(self, app_label):
        return True

我在以 Cannot assign "OrderedDict([('username', 'api_test'), ('password', 'test@123')])": "AuthToken.user" must be a "User" instance.

提交登录时收到值错误

我认为 Django/Knox 无法在我的 LoginSerializer 中获得 useruser.is_active。我已经从初始迁移中启动了我的用户模型。

任何解决此问题的帮助都会很棒。谢谢。

在这部分代码中:

 return Response({
        "user": UserSerializer(user, context=self.get_serializer_context()).data,  # Get serialized User data
        "token": token
    })

您需要将令牌替换为该令牌所属的用户实例,例如:

 return Response({
            "user": UserSerializer(user, context=self.get_serializer_context()).data,  # Get serialized User data
            "token": User.objects.get(token=token)
        })