1

I want to include an initialized data structure in my request object, making it accessible in the context object from my templates. What I'm doing right now is passing it manually and tiresome within all my views:

render_to_response(...., ( {'menu': RequestContext(request)}))

The request object contains the key, value pair which is injected using a custom context processor. While this works, I had hoped there was a more generic way of passing selected parts of the request object to the template context. I've tried passing it by generic views, but as it turns out the request object isn't instantiated when parsing the urlpatterns list.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Anders
  • 856
  • 1
  • 7
  • 14
  • one way could be to implement my own render_to_response shortcut, which wraps the django implementation. – Anders Mar 23 '10 at 09:29
  • Search for http://stackoverflow.com/search?q=%5Bdjango%5D+middleware and http://stackoverflow.com/search?q=%5Bdjango%5D+context for numerous questions closely related to this one. – S.Lott Mar 23 '10 at 10:14
  • Exact Duplicate: http://stackoverflow.com/questions/2269508/django-template-context-processor-request-variable – S.Lott Mar 23 '10 at 10:15

2 Answers2

1

To accomplish this, you will probably have to create your own middleware. That way, you have full control of the request, both before and after the view function.

Middleware is a very powerful concept, and not as hard to implement as it could seem, but don’t overdo it – it makes it hard to follow the program flow.

mikl
  • 23,749
  • 20
  • 68
  • 89
  • Yeah, that seemed to be the way to go. It correctly decorates my request object. We made a custom shortcut to replace 'render_to_response' - it simply uses 'render_to_response', but it passes along the RequestContext(request) argument, too! – Anders Apr 07 '10 at 18:19
0

I don't necessarily understand your question well enough.

Either you are complaining having to include the RequestContext in all views, in which case you need to write a wrapper that passes RequestContext for you. But you will still have to pass to it the request. If you don't want to pass that too, you may have to create your own middleware as mikl suggests.

Or, you are complaining about having to pass a lot of menu items, in each and every view. Which is wrong way to do it, you need to define a template context processor that ensures these are present in the template by default.

lprsd
  • 84,407
  • 47
  • 135
  • 168