user1830568
user1830568

Reputation: 505

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?

Upvotes: 0

Views: 116

Answers (1)

Bernhard Vallant
Bernhard Vallant

Reputation: 50796

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!

Upvotes: 4

Related Questions