Search code examples
djangodjango-context

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}

Solution

  • 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}