用于经过身份验证的用户的条件上下文处

时间:2010-07-05 01:43:28

标签: django django-context

我有一个上下文处理器返回用户朋友列表。我希望它只在用户登录时返回朋友字典,因为目前我有没有任何用户的干净数据库而且我收到错误:

Exception Type: DoesNotExist at /
Exception Value: UserProfile matching query does not exist.

这是我尝试的两个版本,但没有任何运气。为什么它仍然在不应该搜索匹配的用户?

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}

2 个答案:

答案 0 :(得分:4)

我不知道你的系统是如何创建UserProfiles的,但即使用户登录时也可能看起来没有UserProfile。假设UserProfile可能不存在,您应该编写代码:

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}

答案 1 :(得分:0)

您收到错误,因为在同步时创建管理员不会创建您的UserProfile,因此UserProfile.get()会引发DoesNotExist异常。

改变这个:

userprofile = UserProfile.objects.get(user=request.user)

为:

userprofile,created = UserProfile.objects.get_or_create(user=request.user)

你没事。

相关问题