Django user.is_authenticated 在某些地方有效,在其他地方无效
在我的模板中,我有以下内容:
<ul class="tabbed" id="network-tabs">
{% if user.is_authenticated %}
<li><a href="{% url acct-my-profile %}">My Account</a></li>
<li><a href="{% url acct-logout %}">Log Out</a></li>
{% else %}
<li><a href="{% url acct-login %}">Log in</a></li>
<li><a href="{% url acct-register %}">Register</a></li>
{% endif %}
</ul>
它似乎工作正常,除非创建的页面具有 @login_required 装饰器,在这种情况下,页面工作正常,但导航看起来好像用户未登录,即使他们已登录。
In my template, I have the following:
<ul class="tabbed" id="network-tabs">
{% if user.is_authenticated %}
<li><a href="{% url acct-my-profile %}">My Account</a></li>
<li><a href="{% url acct-logout %}">Log Out</a></li>
{% else %}
<li><a href="{% url acct-login %}">Log in</a></li>
<li><a href="{% url acct-register %}">Register</a></li>
{% endif %}
</ul>
It seems to work fine, unless the page been created has a @login_required decorator, in which case the page works fine but the navigation appears as if the user is not logged in, even when they are.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该检查您的视图函数以查看
user
变量来自何处。除非您专门将user
从视图传递到上下文中,否则这就是您的问题。不过,您确实可以访问
request.user
,并且在从具有@login_required
的视图呈现的模板中始终返回true装饰师。我可以肯定地告诉你装饰器没有任何问题的原因是在
User
和AnonymousUser
的代码中(位于django.contrib .auth.models
),is_authenticated
方法严格为User
返回 true,为AnonymousUser
返回 false。装饰器不会也不能改变这一点。这意味着您的模板实际上并没有在您检查user
时获取User
对象。You should check your view function to see where the
user
variable is coming from. Unless you're specifically passinguser
into the context from the view, that's your problem.You do have access to
request.user
, though, and that will always return true in a template rendered from a view that has the@login_required
decorator.The reason I can tell you for certain that there's nothing wrong with the decorator, though, is that in the code for
User
andAnonymousUser
(located indjango.contrib.auth.models
) theis_authenticated
method strictly returns true forUser
and false forAnonymousUser
. The decorator does not and cannot change that. And what that means is that your template isn't actually getting aUser
object where you're checkinguser
.根据 Gabriel 的回答,
user
变量是否来自身份验证上下文处理器?如果是,并且您使用的是render_to_response
快捷方式,则需要使用RequestContext
实例。To follow on from Gabriel's answer, is the
user
variable coming from the auth context processor? If it is, and you are using therender_to_response
shortcut, you need to use aRequestContext
instance.