且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查用户是否已登录(如何正确使用user.is_authenticated)?

更新时间:2023-11-28 13:34:52

针对Django 1.10+的更新:is_authenticated现在是Django 1.10中的一个属性.为了向后兼容,该方法仍然存在,但是将在Django 2.0中删除.

Update for Django 1.10+: is_authenticated is now an attribute in Django 1.10. The method still exists for backwards compatibility, but will be 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.