【发布时间】:2009-11-16 05:19:21
【问题描述】:
我有一个应用程序使用平面页面和其他不采用 request 对象的构造。这会导致 base.html 出现问题。这是一个简单的例子。
如果我想要“欢迎 {{ request.user.username }}!”之类的内容在每一页的顶部,最好的方法是什么?
【问题讨论】:
标签: django authentication orm
我有一个应用程序使用平面页面和其他不采用 request 对象的构造。这会导致 base.html 出现问题。这是一个简单的例子。
如果我想要“欢迎 {{ request.user.username }}!”之类的内容在每一页的顶部,最好的方法是什么?
【问题讨论】:
标签: django authentication orm
平面页面在rendering templates 中使用RequestContext。这里有更多关于RequestContext 的信息。可以这么说,您应该能够编写一个上下文处理器来将 request.user 添加到每个模板的上下文中。像这样的:
def user(request):
"""A context processor that adds the user to template context"""
return {
'user': request.user
}
然后将其添加到 settings.py 中现有的 TEMPLATE_CONTEXT_PROCESSORS:
TEMPLATE_CONTEXT_PROCESSORS = TEMPLATE_CONTEXT_PROCESSORS + (
'context_processors.user',
)
您只需要确保您的所有视图也将RequestContext 绑定到它们的模板:
return render_to_response('my_template.html',
my_data_dictionary,
context_instance=RequestContext(request))
这是一个很好的read 上下文处理器。它们是一个非常有用的功能。
【讨论】:
user,内置并默认包含一个:django.core.context_processors.auth
【讨论】: