对不起,如果您在我之前提出此问题时尝试过帮助我。不得不删除该问题,因为出于某种原因我不被允许编辑其他信息。
我正在我的django网站上实现用户身份验证。一切正常。我的观点,模型,网址等都已设置完毕。用户可以注册,登录,注销。我遇到的问题是这段代码:
{% 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))
如果启用了auth上下文处理器,则user
已经在模板上下文中,您可以执行以下操作:
{% if user.is_authenticated %}
如果要在模板中访问request
,请确保已启用request context processor。
在您的问题中,您正在使用render_to_response
。自从Django 1.3以来,最好使用render
而不是render_to_response
。使用render_to_response
和RequestContext(request)
在Django <= 1.9中工作,但是从Django 1.10开始,如果你想让上下文处理器工作,你必须使用render
快捷方式。
return render(request, 'template/login.html', context)
请注意,自Django 1.10以来,is_authenticated
用@property修饰,它的行为不同。
对于UNAUTHENTICATED用户调用{{user.is_authenticated}}结果:
CallableBool(True)
(当Django <1.10时,它是True
)
对于AUTHENTICATED用户调用{{user.is_authenticated}}结果:
CallableBool(False)
(当Django <1.10时,它是False
)
如果你需要传递例如你的javascript值,如true
或false
you可以使用应用过滤器|yesno:"true,false"
<script language="javascript">
var DJANGO_USER = "{{user.is_authenticated|yesno:"true,false"}}";
</script>