0

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)
DaynaJuliana
  • 1,144
  • 1
  • 14
  • 33

1 Answers1

1

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
spiegelm
  • 65
  • 7
  • Would this go in the `models.py` or `views.py` file ? – DaynaJuliana Nov 13 '15 at 01:14
  • This would go into the `models.py` file, I updated the answer. You may need to adjust your fields in `class User` to match `django.contrib.auth.models.User`, i.e. rename or remove fields, that are already present in Djangos class. For example the fields `first_name`, `last_name` and `email` already exist and do not need to be overridden. – spiegelm Nov 13 '15 at 01:22
  • I already have a `class User(models.Model):`, would this `class User(user)` be seperate? – DaynaJuliana Nov 13 '15 at 01:33
  • 1
    No, the line `class User(User):` would be instead of `class User(models.Model):`, i.e. the class User inherits from Djangos User class instead of `models.Model`. Don't forget the import line on the top. – spiegelm Nov 13 '15 at 01:36
  • OK but isn't this bad practice? should I rename my user ? – DaynaJuliana Nov 13 '15 at 02:06
  • Yes, you're right, this looks confusing. You could either rename your user class, for example: `class MyUser(User):`. Or you could modify the import `from django.contrib import auth` and define the User model like this: `class User(auth.models.User):`. I'll update the anser. – spiegelm Nov 13 '15 at 02:25
  • What if I don't have a username or password, its not working due to non-uniquness when null – DaynaJuliana Nov 13 '15 at 02:36