如果我之前问你的时候你想帮我,我很抱歉.我不得不删除这个问题,因为出于某种原因,我不能编辑额外的信息.

我正致力于在我的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))

推荐答案

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

{% if user.is_authenticated %}

如果要访问模板中的request,请确保已启用request context processor.

在你的问题中,你用的是render_to_response.自从Django 1.3以来,最好使用render而不是render_to_response.在Django使用render_to_responseRequestContext(request)作品<;=1.9,但从Django 1.10开始,如果希望上下文处理器工作,必须使用render快捷方式.

return render(request, 'template/login.html', context)

Django相关问答推荐

Django Signals:从实例访问ManyToManyRel值

如何在对接合成时创建两个Postgres数据库?

创建用户/将用户登录到客户端服务器的标准OAuth/OIDC流程是什么?

在模板中自动添加变量

如何从列中捕获数据并将其添加到下拉菜单中,以便表单填充另一个表

在Python中向函数的查询列表添加条件

Django: 无法将我的 comments 关联到特定产品

在Django测试get方法中获取HttpResponseNotFound

如何在 createsuperuser 中实例化表

- 不支持的操作数类型:DateField和DateField

带有代码完成功能的 python / django 的 Sublime Text 2 和 3 设置

如何让 Django 在模板更改时重新启动运行服务器?

如何使用 jQuery 建立 Django 网站

Django error:不能分配必须是实例

Django App 配置不当 - 应用程序模块有多个文件系统位置

Django 模板列表的第一个元素

带有消息判断的 Django/Python assertRaises

Django JavaScript 文件

在 Django 中注册用户的最佳方法

Django模型字段按变量