About •  Books •  Apps •  Jobs •   Feeds •  Twitter
Login

Keeping user profiles in sync

Django provides a user profile as a way to extend a users information. This isn't created automatically for you however when you create a new User, but it is pretty simple to do this.

The easiest way to do this is to use signals. By listening to the post_save signal on users, you can create a user profile on a save.

When the user object is deleted, the profile will be deleted, because the delete cascades. To use this, don't forget to register in the class UserProfile into AUTH_PROFILE_MODULE (see settings at the end):

from django.db import models
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist

class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True)

def create_profile(sender, **kw):
    user = kw["instance"]
    if kw["created"]:
        up = UserProfile(user=user)
        up.save()

post_save.connect(create_profile, sender=User)

And here's a test to demonstrate it working.

from django.test import TestCase
from models import UserProfile
from django.contrib.auth.models import User

class UserTest(TestCase):
    def testUser(self):
        u = User.objects.create(
             username='admin',
             email='andy@clearwind.ca')

        u.save()
        
        assert u.get_profile()
        assert User.objects.count() == 1
        assert UserProfile.objects.count() == 1
        
        u.delete()
        
        assert User.objects.count() == 0
        assert UserProfile.objects.count() == 0

Since this got asked on the django IRC channel I figured it had enough reason to justify a blog post.

References:

Comments

There are no comments.

Login to add comments