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

标签 python django authentication

我正在查看 this website但似乎无法弄清楚如何做到这一点,因为它不起作用。我需要检查当前站点用户是否已登录(已通过身份验证),并且正在尝试:

request.user.is_authenticated

尽管确定用户已登录,但它只返回:

>

我可以执行其他请求(来自上面 url 的第一部分),例如:

request.user.is_active

返回一个成功的响应。

最佳答案

Django 1.10+ 更新

is_authenticated 现在是 Django 1.10 中的一个属性

if request.user.is_authenticated:
    # do something if the user is authenticated

注意:该方法已在 Django 2.0 中删除。

对于 Django 1.9 及更早版本

is_authenticated 是一个函数。你应该这样调用它

if request.user.is_authenticated():
    # do something if the user is authenticated

正如 Peter Rowell 所指出的,可能会让您感到困惑的是,在默认的 Django 模板语言中,您不会使用括号来调用函数。所以你可能在模板代码中看到过这样的东西:

{% if user.is_authenticated %}

但是,在Python代码中,确实是User类中的一个方法。

关于python - 如何检查用户是否登录(如何正确使用 user.is_authenticated)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3644902/

相关文章:

python - 从文本生成关键字的简单方法是什么?

Python 3.x tkinter : Buttons of specific shapes or Button overlay

python - Django celery beat 属性错误 : 'NoneType' object has no attribute 'localize'

Django 用类型转换变量注释

c# - 登录后如何在下一个表单的标签中显示欢迎用户名?

c# - 在 MVC 4 中限制未登录用户对 Controller 操作的访问

python - 删除没有值的字典条目 - Python

python - 为什么 is 运算符说两个相等的 id 不相同?

Django makemigrations AttributeError : 'str' object has no attribute '_meta'

authentication - 登录时密码什么时候会被加密?