zub*_*hta 2 django django-templates django-authentication
在我的base.html文件中,我正在使用
此处,即使用户已登录,也会显示登录按钮.
{% if user.is_authenticated %}
<a href="#">{{user.username}}</a>
{% else %} <a href="/acc/login/">log in</a>
现在,当我点击log in链接时,它会显示用户名和正常登录视图,表示用户已登录.
那么,怎么了?
听起来你没有在模板中获得任何用户信息.您需要'django.contrib.auth.middleware.AuthenticationMiddleware'在您的MIDDLEWARE_CLASSES设置中,为了获得模板的上下文,您需要:
from django.shortcuts import render_to_response
from django.template import RequestContext
def my_view(request):
return render_to_response('my_template.html',
my_data_dictionary,
context_instance=RequestContext(request))
Run Code Online (Sandbox Code Playgroud)
为了节省你在任何地方这样做,考虑使用django-annoying的 render_to装饰而不是render_to_response.
@render_to('template.html')
def foo(request):
bar = Bar.object.all()
return {'bar': bar}
# equals to
def foo(request):
bar = Bar.object.all()
return render_to_response('template.html',
{'bar': bar},
context_instance=RequestContext(request))
Run Code Online (Sandbox Code Playgroud)