tags:

views:

236

answers:

1

This is a very similar question to this SO thread on middleware and views communicating

We'd like to have our templates be given a standard set of context variables. So, a context processor seems appropriate, however, it doesn't seem like the context processor is view-aware. We'd previously been forced to inspect the call stack to get contextual information on what view was doing what.

That's where we saw the middleware thread as well as the process_view() signature for a middleware that gives us a handle to the view.

This seemed closer to our needs, but didn't allow us to modify the context variable, neither did the other middleware methods.

So our intial idea bandied about was to modify the request object with all the global and contextual information we needed for our templates and force the templates to call from the {{request.something}} for the specific information we need, such as {{request.viewname}}.

So, our questions:

  • Is modifying/setting values on the request object an accepted thing to do for pushing contextual/global app specific information to your templates? Or is the standard practice always to put it into contexts?
  • Are there ways/tricks to make context processors view aware that don't involve passing it explicitly or doing some stack introspection?
  • Does the middleware.process_response have an opportunity to modify the context or is it immutable?
+2  A: 

It's perfectly valid to set variables on the request in middleware - I do it all the time.

There's no way to use process_response for this, as by then the template has already been rendered - at this point all you get is an HttpResponse containing a bunch of HTML.

An alternative might be to wrap render_to_response with your own function, which takes the context, together with the request and template, and modifies it as necessary before handing off to the actual render function. This has the advantage of modifying the actual context, but the disadvantage that you have to actually remember to call it in every view instead of the default function.

Daniel Roseman
See also http://jboxer.com/2009/05/django-middleware-vs-context-processors/
Ztyx