July 29, 2010

Conditional context processor for authenticated users

Recently I needed a context processor to display friends of my logged user. Userprofile is the name for extended user model. Here's the code :

def friends_list(request):
    try:
        user = request.user
    except User.DoesNotExist:
        user = AnonymousUser()
    
    userprofile = None
    try:
        userprofile = UserProfile.objects.get(user=request.user)
    except UserProfile.DoesNotExist:
        pass
    if userprofile:
        friends = Friend.objects.filter(friend_of=userprofile)
    else:
        friends = {}
    return {'friends': friends}

No comments:

Post a Comment