views:

108

answers:

2

I have extended the user model using the UserProfile method. However I occasionally get the Django error message UserProfile matching query does not exist when running the query request.user.get_profile()

I think this is happening when I have become logged out of the system so my user becomes an AnonymousUser. Is there any way I can automatically redirect the user back to the login page if a UserProfile does not exist.

I am using request.user.get_profile() in quite a few places so don't really want to go through my code putting checks on everyone so was thinking of a way using signals or something similar where I only have to do it once.

Also I am using @login_required on my function calls but this doesn't seem to be redirecting the user before they get this error.

Every registered user should have a UserProfile account as this is automatically created if they don't have one when they log into the system.

I am also using Django 1.1

A: 

so was thinking of a way using signals or something similar where I only have to do it once.

AFAIK you cannot do this with a signal.

You can however create a custom decorator to replace login_required. This decorator can wrap login_required and check for user profile. You can then replace Django's login_required with your own in the import statement.

Manoj Govindan
I'm not familiar with custom decorators. Can you give me an example of how to do this?
John
A: 

The @login_required decorator ensures that the user is logged in. This error is probably occurring because some user records don't have a UserProfile. You can test this in the shell

from django.contrib.auth.models import *
for u in User.objects.all():
    try:
        u.get_profile()
    except:
        print "%s does not have a profile" % u
Jordan Reiter