小编典典

Django模板中的user.is_authenticated遇到麻烦

django

当我较早前问到你时是否尝试帮助我。必须删除该问题,因为由于某些原因不允许我编辑其他信息。

我正在django网站上实施用户身份验证。一切正常。我的视图,模型,URL等均已设置。用户可以注册,登录和注销。我遇到的问题是这段代码:

{% if request.user.is_authenticated %}
      <li><a href="/logout">Log Out</a></li>
      {% else %}
      <li><a href="/login">Log In</a></li>
      {% endif %}

即使登录后,它仍会显示“登录”作为选项,而不是“注销”。但是,如果我单击链接,它将把我重定向到/ profile,因为如果我登录,该视图就会告诉我执行该操作。因此,很明显它知道我已登录,但是模板不是readint user.is_authenticated为true。

与登录请求有关的视图是:

def LoginRequest(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect('/profile/')
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            profile = authenticate(username=username, password=password)
            if profile is not None:
                login(request, profile)
                return HttpResponseRedirect('/profile/')
            else:
                return render_to_response('template/login.html', {'form': form}, context_instance=RequestContext(request))
        else:
            return render_to_response('template/login.html', {'form': form}, context_instance=RequestContext(request))
    else:
        ''' user is not submitting the form, show them login form ''' 
        form = LoginForm()
        context = {'form': form}
        return render_to_response('template/login.html', context, context_instance = RequestContext(request))

阅读 1389

收藏
2020-04-03

共1个答案

小编典典

如果启用了身份验证上下文处理器,则user该模板上下文中已经存在该处理器,你可以执行以下操作:

{% if user.is_authenticated %}

如果要访问request模板,请确保已启用请求上下文处理器。

在你的问题中,你正在使用render_to_response。从Django 1.3开始,最好使用render代替render_to_response。在Django <= 1.9中使用render_to_responsewith RequestContext(request)可以工作,但是从Django 1.10开始,如果要使用render上下文处理器,则必须使用快捷方式。

return render(request, 'template/login.html', context)
2020-04-03