Search code examples
pythondjangodjango-users

Attribute error in extending django user model?


I have done this before and got it working fine. Is this because i'm using django2.0?

models.py

class Profile(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    ....

 @receiver(post_save, sender=User)
 def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)

 @receiver(post_save, sender=User)
    def save_user_profile(sender, instance, **kwargs):
        instance.profile.save()

I get the error AttributeError: 'User' object has no attribute 'profile'. I don't get it?


Solution

  • To access all reverse related by ForeignKey profiles you need to use profile_set. If you need to obtain and save first related object try this:

    def save_user_profile(sender, instance, **kwargs):
        instance.profile_set.first().save()
    

    But in this situation I believe you'd better use OneToOneField:

    user = models.OneToOneField(User, on_delete=models.CASCADE)
    

    which allows to create only one related profile and also will allow to this syntax:

    def save_user_profile(sender, instance, **kwargs):
        instance.profile.save()