Login

User post_save signal to auto create 'admin' profile

Author:
marinho
Posted:
December 8, 2007
Language:
Python
Version:
.96
Score:
8 (after 8 ratings)

How to use:

  1. puts this code at the end of the models.py file who haves the User Profile class declared;
  2. verify if your User Profile class has the name 'UserProfile'. If not, change the code to the right name.

About: this snippet makes the ORM create a profile each time an user is created (or updated, if the user profile lost), including 'admin' user.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# SIGNALS AND LISTENERS
from django.contrib.auth.models import User
from django.db.models import signals
from django.dispatch import dispatcher

# User
def user_post_save(sender, instance, signal, *args, **kwargs):
    # Creates user profile
    profile, new = UserProfile.objects.get_or_create(user=instance)

dispatcher.connect(user_post_save, signal=signals.post_save, sender=User)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

JoshuaJenkins (on November 11, 2008):

This is no longer valid as the way dispatcher works has been updated.

Any shot at an update?

#

sasha (on November 12, 2008):

For Django 1.0:

def user_post_save(sender, instance, **kwargs):
    profile, new = UserProfile.objects.get_or_create(user=instance)

models.signals.post_save.connect(user_post_save, sender=User)

#

ori (on February 21, 2011):

For Django 1.3, using the new @receiver decorator:

from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
    """Create a matching profile whenever a user object is created."""
    if created: 
        profile, new = UserProfile.objects.get_or_create(user=instance)

#

thisnameagain (on May 11, 2011):

Hello, was playing around with signals and came across an issue. Was able to use the receiver decorator approach from Ori when using the built in signals (i.e. post_save, etc.) put when I tried to use that approach with a custom signal it does not work.

I confirmed that the custom signal works if I use the approach

custom_signal.connect(custom_receiver)

and all works. but

@receiver(custom_receiver, sender=MyModel) def signal_receiver(sender, **kwargs) print 'in signal_receiver'

This does not work, does the decorator approach not work with custom signals?

Thanks

#

Please login first before commenting.