Django Auth Token ValueError When Assigning to Use

2019-09-12 16:53发布

I'm currently following the Django guide and using the receiver to assign an auth token. However, the following retuens the error

Cannot assign "<User: User object>": "Token.user" must be a "User" instance.

##PRE CREATE Method
@receiver(post_save, sender=User)  
def create_auth_token(sender, instance=None, created=False, **kwargs):
    if created:
        Token.objects.create(user=instance)

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

Even replacing the @receiver with does not work

 def perform_create(self, serializer):
    user = serializer.save()
    Token.objects.create(user=user)

1条回答
虎瘦雄心在
2楼-- · 2019-09-12 17:20

What do your imports look like? Is there another class User beside django.auth.models.user?

Try to inherit your User class from django.contrib.auth.models.User:

models.py:

from django.contrib import auth

class User(auth.models.User):
    # place for extra fields
查看更多
登录 后发表回答