render_to_response总是传递一个变量

时间:2010-02-11 12:39:31

标签: django django-context

我发现自己总是将“用户”变量传递给每次调用render_to_response

我的很多渲染都是这样的

return render_to_response('some/template', {'my':context,'user':user})

有没有办法自动发送这个'user'变量,而无需在每次调用方法时手动将其添加到上下文中?

4 个答案:

答案 0 :(得分:11)

首先,阅读this。然后:

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

答案 1 :(得分:2)

是的,您可以使用上下文处理器执行此操作:http://docs.djangoproject.com/en/dev/ref/templates/api/#id1

实际上,如果在上下文处理器中包含DJANGO.CORE.CONTEXT_PROCESSORS.AUTH,则会将用户添加到每个请求对象中。 http://docs.djangoproject.com/en/dev/ref/templates/api/#django-core-context-processors-auth

您需要像其他人提到的那样使用context_instance=RequestContext(request)来使用上下文处理器。

答案 2 :(得分:0)

您可能希望查看render_to,它是django-annoying的一部分 - 它允许您执行以下操作:

@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)来包装你。

答案 3 :(得分:0)

Dimitry是对的,但您可以使用direct_to_template通用视图作为常规函数来进一步简化此操作。它的源代码是here

还有一个很好的附加组件django-annoying,它提供render_to装饰器做类似的事情,但不需要显式模板渲染。

相关问题