Django user.is_authenticated works some places, not others

橙三吉。 提交于 2019-12-05 11:11:32

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.

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 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.

To follow on from Gabriel's answer, is the user variable coming from the auth context processor? If it is, and you are using the render_to_response shortcut, you need to use a RequestContext instance.

from django.template import RequestContext

...

@login_required
def some_view(request):
    # ...
    return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!