Middleware that injects data for template

17 views
Skip to first unread message

Stodge

unread,
Jul 24, 2009, 3:24:28 PM7/24/09
to Django users
Say I want to inject a piece of data into every page view. For now,
let's just say I want to inject the current time into each page view.
I write a piece of middleware that will do it. But how? Do I modify
the request? Or the view (process_view)?

Tim Chase

unread,
Jul 24, 2009, 3:49:36 PM7/24/09
to django...@googlegroups.com

I understand that this should be done by modifying the request in
your middleware and then making use of it in your templates (if
it's to appear on every page, it may (or may not) make sense to
put it in your base.html template). This assumes your views are
using a RequestContext which pass the request object into the
template as part of the rendering context.

-tim


Daniel Roseman

unread,
Jul 25, 2009, 4:58:07 AM7/25/09
to Django users
The best way to do this is not in middlware, but in a context
processor - this is exactly what they're for. See here for
documentation:
http://docs.djangoproject.com/en/dev/ref/templates/api/#id1
although basically it's just a matter of writing a function that
returns a dictionary which is added to the context, adding the
function name to TEMPLATE_CONTEXT_PROCESSORS in your settings, and
ensuring that your views use RequestContext.
--
DR.
Reply all
Reply to author
Forward
0 new messages