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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@joshua-koehler , @Bhupesh-V apologies for the delayed response.
The statement
instance.Profile.save()
(whereinstance
is an object ofUser
) is valid. The only issue in the code is implicit declaration of therelated_name
param inuser
fielduser = models.OneToOneField(User, on_delete=models.CASCADE)
.So, the explicit declaration of the
related_name
param inuser
field should be:user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
.Note: the addition of param
related_name='profile'
.Ref: https://docs.djangoproject.com/en/4.0/ref/models/fields/#onetoonefield