“ AnonymousUser”对象不可迭代 [英] 'AnonymousUser' object is not iterable

查看:100
本文介绍了“ AnonymousUser”对象不可迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

if not request.user.is_authenticated:
    return None

try:
    return ClientProfile.objects.get(user=request.user)
except ClientProfile.DoesNotExist:
    return None

此代码应如果我尚未登录并尝试调用它,则返回None。但是,正如我从stacktrace中看到的那样,它在此行崩溃,并显示错误'AnonymousUser'对象不可迭代:

This code should return None, if I'm not logged in and trying to call it. But as I see from stacktrace, it crashes with error "'AnonymousUser' object is not iterable" on this line:

return ClientProfile.objects.get(user=request.user)

我正在以私有模式浏览以下页面,因此我100%未通过身份验证。

I'm browsing the following page in private mode, so I'm 100% not authenticated.

如何解决此问题?

推荐答案

在Django 1.9和早些时候, is_authenticated() 是一种方法,必须调用它。

In Django 1.9 and earlier, is_authenticated() is a method, you must call it.

if not request.user.is_authenticated():
    ...

这是一个容易犯的错误忘记调用该方法。在您的情况下,这会导致错误,但在其他情况下,则可能会允许用户访问不该访问的数据。从Django 1.10开始, is_authenticated 更改为属性以防止这种情况。

It's an easy mistake to forget to call the method. In your case it's causing an error, but in other cases it might allow users to have access to data that they shouldn't. From Django 1.10, is_authenticated is changing to a property to prevent this.

这篇关于“ AnonymousUser”对象不可迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆