在我的 base.html 文件中,我使用
的是 Here,即使用户已登录,也会显示登录按钮。
{% if user.is_authenticated %}
<a href="#">{{user.username}}</a>
{% else %} <a href="/acc/login/">log in</a>
现在,当我单击log in
链接时,它会显示用户名以及正常的登录视图,表示用户已登录。
那么,怎么了?
在我的 base.html 文件中,我使用
的是 Here,即使用户已登录,也会显示登录按钮。
{% 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))
为了节省您在任何地方都这样做,请考虑使用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))
我相信多米尼克罗杰的回答可以解决你的问题。只是想补充一点,我个人更喜欢导入direct_to_template
而不是render_to_response
:
from django.views.generic.simple import direct_to_template
...
return direct_to_template(request, 'my_template.html', my_data_dictionary)
但我想这只是口味问题。在我的情况下,您也可以使用命名参数而不是my_data_dictionary
:
return direct_to_template(request, 'template.html', foo=qux, bar=quux, ...)