is_authenticated 对 AnonymousUser 返回 True
当我未登录时,我正在努力解决 is_authenticated
返回 True
的问题:
u = request.user
if u.is_authenticated:
raise Exception('I am said to be authenticated, but I really am not.')
澄清一下,Django 调试视图正确地将 u
识别为 AnonymousUser
:
u <django.contrib.auth.models.AnonymousUser object at 0x9e76f4cc>
更奇怪的是,在模板内 is_anonymous
工作正常:
{% if not request.user.is_authenticated %}
We are anonymous.
{% endif %}
这是为什么?
I am struggling with is_authenticated
returning True
when I'm not logged in:
u = request.user
if u.is_authenticated:
raise Exception('I am said to be authenticated, but I really am not.')
To clarify, Django debug view correctly identifies u
as an AnonymousUser
:
u <django.contrib.auth.models.AnonymousUser object at 0x9e76f4cc>
Even more odd, inside the template is_anonymous
works fine:
{% if not request.user.is_authenticated %}
We are anonymous.
{% endif %}
Why is that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一个 方法,不是财产。你需要调用它:
当然,在模板中,Django 自动为您调用方法。
It's a method, not a property. You need to call it:
Of course, in a template, Django calls methods for you automatically.
is_authenticated
是一种方法,因此您需要一些括号。否则,u.is_authenticated
是函数对象,它是一个True
ish 值。在模板语言中,没有参数的函数被评估为函数,所以这就是你擅长的原因。
is_authenticated
is a method, so you need some parentheses there. Otherwise,u.is_authenticated
is the function object, which is aTrue
ish value.In the template language, functions with no arguments are evaluated as functions, so that's why you're good there.