python - Django:is_authenticated 和 is_anonymous 在注销后都返回 true

标签 python django templates authentication django-registration

我正在使用 django-registration,只需设置它即可。

{{user.is_authenticated }}

是真的,即使我已经去了/accounts/logout/并注销了用户。

{{user.is_anonymous }} 

也返回 true。根据 django 文档,这两个应该是不同的:

is_anonymous: Always returns False. This is a way of differentiating User and AnonymousUser objects. Generally, you should prefer using is_authenticated() to this method.

is_authenticated: Always returns True. This is a way to tell if the user has been authenticated. This does not imply any permissions, and doesn't check if the user is active - it only indicates that the user has provided a valid username and password.

我正在使用 django-registration 附带的标准 View ,但尚未触及它们。在模板中,我有以下代码:

{% if user.is_authenticated %}
{% user }}
{% if user.is_anonymous %}
    is anonymous
{% endif $}
{% else %}
    gotta login
{% endif %}

问题出在哪里?我将非常感激!

更新: 我注意到在主页上,is_authenticated 和 id_anonymous 都返回 True,而如果我在登录前转到/accounts/login,只有 is_anonymous 返回 true,因为它应该是。而且,在主页上,如果有帮助,我有以下 View :

def home(request):
    return render_jinja(request, 'index.html', blah = 'ga')

更新 2: print(request.user.is_authenticated()) 给出 False。然后,我有:

return render_jinja(request, 'index.html', blah = 'ga')

并且在模板中,user.is_authenticated 返回 FALSE。

更新 3: 如果我使用 render_to_response,而不是 render_jinja,一切都很好。仍然不知道如何解决这个问题:(

最佳答案

您似乎正试图同时解决两件事;使用 jinja 模板的正确方法是什么?用户/匿名用户的处理方式是什么。也许尝试一次解决这些问题。

我没有使用 jinja 的经验,但您可能需要检查并确保您正在使用 differences between jinja and django template syntax考虑到。我所知道的最大区别是方法调用需要显式括号。因此,示例中的 is_authenticated 和 is_anonymous 调用需要括号。

Jinja style {{ user.is_authenticated() }}
Django style {{ user.is_authenticated }} 

如果这不能解决问题,请尝试安装 django-debug-toolbar并查看模板的上下文。检查并查看 user 是 None 还是一个对象(User 或 AnonymousUser)。

您还可以阅读 AnonymousUser并查看 checking for an authenticated user 的示例在文档中。简而言之,对于 AnonymousUser 对象,is_anonymous() 总是返回 True 而不是 False,而 is_authenticated() 总是返回 False 而不是 True。

关于python - Django:is_authenticated 和 is_anonymous 在注销后都返回 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4298387/

相关文章:

python - 如何使用 `colorbar` 调色板将 `networkx` 添加到 `seaborn`? ( python 3)

python - 使用批量渲染时如何从屏幕上删除对象(标签、图形)?

python - 显示不带秒的 TimeField 值 - Django

c++ - 带有模板函数的未解析外部符号

C++ - 无法推导出模板参数

Python sympy 方程矩阵

python - 拟合模型时,batch size 和 epoch 的数量应该有多大?

django - RegisterForm() 缺少 1 个必需的位置参数 : 'request'

html - 可以为 Django 中的扩展 html 模板定义一个单独的 css 文件吗?

templates - MediaWiki以及如何通过模板获取页面列表