Question

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?

Was it helpful?

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

OTHER TIPS

This is easy. If you have supplied just a little bit more code in your example the answer might have bit you.

# first build your context, including all of the context_processors in your settings.py
context = RequestContext(request, <some dict values>)
# do something with your Context here
return render_to_response('template.html', context)

Update to comment:

The result of a render_to_response() is an HTTPResponse object containing a template rendered against a Context. That object does not (to my knowledge) have a context associated with it. I suppose you could save the result of render_to_response() in a variable and then access the Context you passed it, but I'm not sure what problem you are trying to solve.

Did you modify the Context during rendering? If so you may find that the information is not there any longer because the Context has a scope stack which is pushed/popped during template processing.

You can create a dictonary for the context:

def myview(...):
    c = dict()
    c["variable"] = value
    ...
     do some stuff
    ...
    return render_to_response('template.html',c)

Maybe the RequestContext is the thing you are looking for.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top