使用装饰器向render_to_response添加上下文

时间:2013-06-22 19:56:07

标签: python django decorator

我有一个观点:

@add_value
my_view(request):
   render_to_response('template.html', {'var1' : 'value'})

和装饰者:

def add_value():

    def decorator(view_func):
        def _decorator(request, *args, **kwargs):
            response = view_func(request, *args, **kwargs)
            #what code can I put in here to add { 'var2' : 'value' } to render_to_response context?

我希望装饰者添加一个密钥对,因此最终的render_to_response将变为以下内容:

render_to_response('template.html', {'var1 : 'value', 'var2' : 'value'})
谁知道怎么做?

1 个答案:

答案 0 :(得分:4)

这样做是不可能的,因为视图已经返回一个现成的HttpResponse对象。但是,如果您想在多个视图的上下文中添加内容,context processor可能就是您要找的内容:

def add_value_context_processor(request):
    return {'var': value}

并将其添加到settings.py中的TEMPLATE_CONTEXT_PROCESSORS