Search code examples
djangodjango-modelsdjango-authenticationdjango-registration

Django save abuser profile object when user registered


Hi I have a customUserProfile model which I will be using for storing user data specific to my app:

from django.contrib.auth.models import User

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    ...

    def __unicode__(self):
        return self.user.username

I am using django-registration to resister and login users.

My question is - what is the best way to auto-save a UserProfile object when an auth.User is saved? I can assume that all custom fields on the UserProfile model can be saved as null and updated later.

Any help much appreciated.


Solution

  • Django Signals could be a good option. So, whenever the User object is saved it would create an User Profile

    class UserProfile(models.Model):
        user = models.OneToOneField(User)
    
    def _create_user_profile(sender, instance, created, **kwargs):
        UserProfile.objects.create(user=instance)
    
    post_save.connect(_create_user_profile, sender=User)