Auto-creating Django Profiles

March 26, 2011

My code tries its best to recover if a user doesn't have a user profile, but it was becoming too much of a headache to create every time it didn't exist.

Django provides hooks to allow you to create the profile when it doesn't exist. Add the following code to your models file that contains UserProfile class.

from django.db.models.signals import post_save

def create_user_profile(sender, instance, created, **kwargs):
    """
    Create user profile for new users at save user time, if it doesn't already exist
    """
    if created:
        UserProfile(user=instance).save()

post_save.connect(create_user_profile, sender=User)

Be wary when using this from automated tests. I had some test fixtures that included both User and UserProfile instances. When Django's test framework read the fixture file and inserted the users, this triggered the signal, which created the profiles in the database. When the test fixture then reached the profiles, it created some more profiles, so I had two for each user. Subtle, and confusing! I fixed this by deleting the profiles from the fixture test file, and relying on the signal to create the profile.

Tags: django profile