我发现自己总是传递一个“用户”变量每次调用render_to_response
总是选择render_to_response传递一个变量
我的很多渲染这个样子的
return render_to_response('some/template', {'my':context,'user':user})
是否有办法来自动发送这个'user'变量时,每次调用方法时都不需要手动将其添加到上下文中?
我发现自己总是传递一个“用户”变量每次调用render_to_response
总是选择render_to_response传递一个变量
我的很多渲染这个样子的
return render_to_response('some/template', {'my':context,'user':user})
是否有办法来自动发送这个'user'变量时,每次调用方法时都不需要手动将其添加到上下文中?
首先,阅读this。然后:
def some_view(request):
# ...
return render_to_response('my_template.html',
my_data_dictionary,
context_instance=RequestContext(request))
你可能想看看render_to
,这是Django的恼人的一部分 - 它允许你做这样的事情:
@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))
你可以写一个类似的装饰(如render_with_user_to
),包装与你一起。
Dimitry是正确的,但您可以通过使用direct_to_template通用视图作为常规函数来进一步简化此操作。它的源代码是here。
还有不错的附加组件,django-annoying
,它提供了render_to装饰器做类似的事情,但不需要显式模板渲染。如果包括DJANGO.CORE.CONTEXT_PROCESSORS.AUTH在context处理器,则用户将被添加到每个请求对象http://docs.djangoproject.com/en/dev/ref/templates/api/#id1
事实上:
是的,你可以用上下文处理器做到这一点。 http://docs.djangoproject.com/en/dev/ref/templates/api/#django-core-context-processors-auth
像其他人提到的那样,您需要使用context_instance=RequestContext(request)
以使用上下文处理器。