简体   繁体   中英

Add context to render_to_response using decorators

I have a view:

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

and a decorator:

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?

I would like the decorator to add a key pair, so the final render_to_response will become the following:

render_to_response('template.html', {'var1 : 'value', 'var2' : 'value'})

anyone know how to do this?

It is not possible like you're trying to do it, as the view already returns a readymade HttpResponse object. But if you want to add something to the context of more than one view a context processor might be what you are looking for:

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

And add it to TEMPLATE_CONTEXT_PROCESSORS in your settings.py !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM