Last active
January 22, 2023 07:02
-
-
Save toransahu/f0bd7313c24605ce92d38a7b09caf4b4 to your computer and use it in GitHub Desktop.
Django | Extend User Model | Using a One-To-One Link | Profile
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
@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
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.