Django - redirect to login page if UserProfile matching query does not exist error
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 l开发者_开发知识库ogin 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
this should work
def profile_required():
def has_profile(user):
try:
user.get_profile()
except:
return False
else:
return True
return user_passes_test(lambda u: has_profile(u))
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.
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
精彩评论