Conditional context processor for authenticated users
I have a context processor returning list of users friends. I'd like it to return the dictionary of friends only if user is logged in, because currently I have clean database without any users and I'm getting error :
Exception Type: DoesNotExist at /
Exception Value: UserProfile matching query does not exist.
Here are two versions I was trying but without any luck开发者_如何转开发. Why it is still searching for matching user when it shouldn't ?
def friends_list(request):
if request.user.is_authenticated:
userprofile = UserProfile.objects.get(user=request.user)
friends = Friend.objects.filter(friend_of=userprofile)
else:
friends = {}
return {'friends': friends}
def friends_list(request):
userprofile = UserProfile.objects.get(user=request.user)
if userprofile:
friends = Friend.objects.filter(friend_of=userprofile)
else:
friends = {}
return {'friends': friends}
I don't know how your system creates UserProfiles, but it looks like even when the user is logged in, there may be no UserProfile for them. You should write your code assuming the UserProfile might not exist:
def friends_list(request):
userprofile = None
if request.user.is_authenticated:
try:
userprofile = UserProfile.objects.get(user=request.user)
except DoesNotExist:
pass
if userprofile:
friends = Friend.objects.filter(friend_of=userprofile)
else:
friends = []
return {'friends': friends}
You are getting an error, because creating the admin while syncing does not create your UserProfile, so UserProfile.get() raises a DoesNotExist exception.
change this:
userprofile = UserProfile.objects.get(user=request.user)
to:
userprofile,created = UserProfile.objects.get_or_create(user=request.user)
and you're fine.
精彩评论