Search code examples
djangodjango-middlewaredjango-context

Django - Access Context Dictionary Before Template


I'm hoping to use a context processor or middleware to modify the values of the dictionary passed to render_to_response prior to the actual rendering. I have a messaging schema I'm trying to implement that would populate a message list based on the existence of a type of user that I'd like to search the context for prior to the rendering of the template.

Example:

def myview(...):
    ...
    return render_to_response('template.html',
        {'variable': variable},
    )

and I'd like to be able to add additional information to the context on the existence of 'variable'.

How can I access 'variable' after my view defines it but before it gets to the template so that I can further modify the context?


Solution

  • use TemplateResponse:

    from django.template.response import TemplateResponse
    
    def myview(...):
        ...
        return TemplateResponse(request, 'template.html', 
            {'variable': variable},
        )
    
    def my_view_wrapper(...):
        response = my_view(...)
        variable = response.context_data['variable']
        if variable == 'foo':
            response.context_data['variable_is_foo'] = True
        return response