Skip to content

Instantly share code, notes, and snippets.

@toransahu
Last active January 22, 2023 07:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save toransahu/f0bd7313c24605ce92d38a7b09caf4b4 to your computer and use it in GitHub Desktop.
Save toransahu/f0bd7313c24605ce92d38a7b09caf4b4 to your computer and use it in GitHub Desktop.
Django | Extend User Model | Using a One-To-One Link | Profile
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.TextField(max_length=500, blank=True)
location = models.CharField(max_length=30, blank=True)
birth_date = models.DateField(null=True, blank=True)
"""
Hooking the create_user_profile and save_user_profile methods to the User model, whenever a save event occurs.
This kind of signal is called post_save.
"""
@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()
@Bhupesh-V
Copy link

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

What does profile refers to ?
I guess the correct line would be
instance.Profile.save()

@joshua-koehler
Copy link

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

What does profile refers to ?
I guess the correct line would be
instance.Profile.save()

I also was confused by this. But I don't think your suggestion is correct either.

instance would be an object of User type, so he is assuming that it has an attribute profile, which it doesn't.

@toransahu
Copy link
Author

toransahu commented Dec 15, 2021

@joshua-koehler , @Bhupesh-V apologies for the delayed response.

The statement instance.Profile.save() (where instance is an object of User) is valid. The only issue in the code is implicit declaration of the related_name param in user field user = models.OneToOneField(User, on_delete=models.CASCADE).

So, the explicit declaration of the related_name param in user field should be: user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile').

Note: the addition of param related_name='profile'.

If you do not specify the related_name argument for the OneToOneField, Django will use the lowercase name of the current model as default value.

Ref: https://docs.djangoproject.com/en/4.0/ref/models/fields/#onetoonefield

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment