tags:

views:

70

answers:

2

I use request.user.get_profile() in a number of places in my code. However not all uses have a user profile assosiated with their account. Is there some way I can create a user profile automatically when calling request.user.get_profile() if they don't have one without having to change each one of my request.user.get_profile() calls. Maybe using signals or something.

The problem I have is that I use a single sign-in login so if someone logs in on another system and then goes to my site they are logged in but don't get a user profile created (I create a user profile when they log in).

A: 

The usual way is to use signals:

def create_user_profile(sender, instance, created, **kwargs):
    if created:
        profile, created = UserProfile.objects.get_or_create(user=instance)

signals.post_save.connect(create_user_profile, sender=User)

See http://stackoverflow.com/questions/44109/extending-the-user-model-with-custom-fields-in-django

jakub
@Jakub: The OP creates profiles at _login_ time. The problem is that they don't always login through the OP's site.
Manoj Govindan
+3  A: 

Usually user profile objects are created right after the user instance is created. This is easily accomplished using signals.

The problem I have is that I use a single sign-in login so if someone logs in on another system and then goes to my site they are logged in but don't get a user profile created (I create a user profile when they log in).

Apparently using signals at user creation time won't work for you. One way to accomplish what you are trying to do would be to replace calls to request.user.get_profile() with a custom function. Say get_or_create_user_profile(request). This function can try to retrieve an user's profile and then create one on the fly if one doesn't exist.

For e.g.:

def get_or_create_user_profile(request):
    profile = None
    user = request.user
    try:
        profile = user.get_profile()
    except UserProfile.DoesNotExist:
        profile = UserProfile.objects.create(user, ...)
    return profile
Manoj Govindan
Thanks. I like this answer but wasn't keen on changing all instances of request.user.get_profile() in my code. Is there not a signal I could attach to the UserProfile post_get (I don't know if this exists)
John
@John: AFAIK there is no built in signal that is sent on `get` (`post_get` as you said). The docs seem to agree http://docs.djangoproject.com/en/dev/ref/signals/
Manoj Govindan
@Manoj: what about doing it through middleware?
John
@John: Yes, now that you mention it I guess it would be possible to intercept a request and create an User Profile. Caveat: I have never tried something like it though.
Manoj Govindan