-
-
Save toransahu/f0bd7313c24605ce92d38a7b09caf4b4 to your computer and use it in GitHub Desktop.
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() |
@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.
@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
What does
profile
refers to ?I guess the correct line would be
instance.Profile.save()