如何检查用户是否登录(如何正确使用 user.is_authenticated)? [英] How to check if a user is logged in (how to properly use user.is_authenticated)?
问题描述
我正在查看这个网站 但似乎无法弄清楚如何执行此操作,因为它不起作用.我需要检查当前站点用户是否已登录(经过身份验证),并且正在尝试:
I am looking over this website but just can't seem to figure out how to do this as it's not working. I need to check if the current site user is logged in (authenticated), and am trying:
request.user.is_authenticated
尽管确定用户已登录,但它只返回:
despite being sure that the user is logged in, it returns just:
>
我可以执行其他请求(来自上面 url 的第一部分),例如:
I'm able to do other requests (from the first section in the url above), such as:
request.user.is_active
返回一个成功的响应.
推荐答案
Django 1.10+ 更新:
is_authenticated
现在是 Django 1.10 中的属性.
is_authenticated
is now an attribute in Django 1.10.
该方法在 Django 2.0 中被移除.
The method was removed in Django 2.0.
对于 Django 1.9 及更早版本:
is_authenticated
是一个函数.你应该这样称呼它
is_authenticated
is a function. You should call it like
if request.user.is_authenticated():
# do something if the user is authenticated
正如 Peter Rowell 指出的那样,可能会让您感到困惑的是,在默认的 Django 模板语言中,您没有附加括号来调用函数.所以你可能在模板代码中看到过这样的事情:
As Peter Rowell pointed out, what may be tripping you up is that in the default Django template language, you don't tack on parenthesis to call functions. So you may have seen something like this in template code:
{% if user.is_authenticated %}
但是,在Python代码中,它确实是User
类中的一个方法.
However, in Python code, it is indeed a method in the User
class.
这篇关于如何检查用户是否登录(如何正确使用 user.is_authenticated)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!