Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django create userprofile if does not exist

Tags:

django

I use request.user.get_profile() in a number of places in my code. However not all users 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).

like image 493
John Avatar asked Sep 14 '10 08:09

John


1 Answers

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
like image 197
Manoj Govindan Avatar answered Sep 19 '22 15:09

Manoj Govindan