用于经过身份验证的用户的条件上下文处理器
我有一个上下文处理器返回用户朋友列表。我希望它仅在用户登录时返回朋友的字典,因为目前我有干净的数据库,没有任何用户,并且我收到错误:
异常类型:DoesNotExist at /
异常值:UserProfile 匹配查询不存在。
这是我尝试过的两个版本,但没有任何运气。为什么它不应该搜索匹配的用户?
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 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}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不知道您的系统如何创建 UserProfiles,但看起来即使用户登录,也可能没有他们的 UserProfiles。您应该假设 UserProfile 可能不存在来编写代码:
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:
您收到错误,因为同步时创建管理员不会创建您的 UserProfile,因此 UserProfile.get() 会引发DoesNotExist 异常。
将其更改
为
:就可以了。
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:
to:
and you're fine.