【问题标题】:Add context to render_to_response using decorators使用装饰器将上下文添加到 render_to_response
【发布时间】:2013-06-22 19:56:07
【问题描述】:

我有一个看法:

@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'})

有人知道怎么做吗?

【问题讨论】:

  • 您不能使用该视图代码,因为在函数返回时渲染已经完成。您可以改为返回 TemplateResponse,这将允许您更改上下文,但正如 Bernhard 的回答所建议的那样,使用上下文处理器可能会更好。

标签: python django decorator


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2013-06-15
    • 1970-01-01
    • 2021-01-05
    • 2018-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-18
    • 2015-01-06
    相关资源
    最近更新 更多