Django user.is_authenticated在某些地方工作,而不是其他地方 [英] Django user.is_authenticated works some places, not others

查看:173
本文介绍了Django user.is_authenticated在某些地方工作,而不是其他地方的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的模板中,我有以下内容:

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>

似乎工作正常,除非创建的页面有@login_required装饰器,在这种情况下页面工作正常,但导航显示为用户未登录,即使他们是。

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.

推荐答案

你应该检查你的查看功能以查看用户变量来自哪里。除非您从视图中将用户专门传递到上下文中,否则这是您的问题。

You should check your view function to see where the user variable is coming from. Unless you're specifically passing user into the context from the view, that's your problem.

do 可以访问 request.user ,并且将始终在从具有 @的视图呈现的模板中返回true login_required 装饰器。

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.

我可以告诉你一些装饰器没有错的原因,但是在用户 AnonymousUser (位于 django.contrib.auth.models is_authenticated 方法对于用户严格返回true,对于 AnonymousUser 。装饰者不会也不能改变。这意味着你的模板实际上并没有获得用户对象,您正在检查用户

The reason I can tell you for certain that there's nothing wrong with the decorator, though, is that in the code for User and AnonymousUser (located in django.contrib.auth.models) the is_authenticated method strictly returns true for User and false for AnonymousUser. The decorator does not and cannot change that. And what that means is that your template isn't actually getting a User object where you're checking user.

这篇关于Django user.is_authenticated在某些地方工作,而不是其他地方的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆