很抱歉,如果您在我之前问这个问题时尝试帮助我。不得不删除该问题,因为由于某种原因我不被允许编辑其他信息。
我正在努力在我的 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
在模板中,确保您已启用请求上下文处理器 https://docs.djangoproject.com/en/1.11/ref/templates/api/#django-template-context-processors-request.
在你的问题中你正在使用render_to_response
。从 Django 1.3 开始,使用起来就更好了render
代替render_to_response
. Using render_to_response
with RequestContext(request)
适用于 Django render如果您希望上下文处理器工作,可以使用快捷方式。
return render(request, 'template/login.html', context)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)