我正在使用django注册,然后设置它。
{{user.is_authenticated }}
是的,即使我已经转到/accounts/logout/并注销了用户。
{{user.is_anonymous }}
也返回true。根据django docs的说法,这两者应该有所不同:
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注册时附带的标准视图,但还没有触及它们。在tempalate中,我有以下代码:
{% if user.is_authenticated %}
{% user }}
{% if user.is_anonymous %}
is anonymous
{% endif $}
{% else %}
gotta login
{% endif %}
问题在哪里?我会非常感激的!
更新: 我注意到,在主页上,它同时是经过身份验证的和id_anonymous return True,而如果我在登录前转到/accounts/login,则只有_anonymous返回True。此外,在主页上,如果有帮助,我有以下视图:
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模板的正确方法是什么,以及如何处理User/AnonymousUser。也许试着一次一个地解决这些问题。
我对金贾没有经验,但你可能想检查一下,确保你考虑到了differences between jinja and django template syntax。我知道的最大区别是方法调用需要显式括号。因此在您的示例中,is_authenticated和is_anonymous调用需要括号。
如果这不能解决问题,请尝试安装django-debug-toolbar,并查看模板的上下文。检查
user
是否为None或对象(User或AnonymousUser)。您还可以阅读AnonymousUser,并在文档中看到checking for an authenticated user的示例。简而言之,对于AnonymousUser对象is_anonymous()总是返回True而不是False,is_authenticated()总是返回False而不是True。
打在头上。我在某个地方读到:
因此,与其在模板中有{{user.is_authenticated},不如应该是{{user.is_authenticated()}
相关问题 更多 >
编程相关推荐