views:

60

answers:

3

Is there a way I can access current context passed by view in custom context processor so I can add missing variable if I want rather than overriding existing variable ?

What I'm trying to Achieve:

I construct my URL's like this /city_slug/ and I want to check if city variable already exist in context, otherwise I want to add city to my context (may be using the last used city stored in session variable otherwise default to some city and may be even set session variable for next use.)

I think this is very common problem, How do you guys solve it ?

A: 

I am not sure if a custom template context processor can do this. From the documentation:

A context processor has a very simple interface: It's just a Python function that takes one argument, an HttpRequest object, and returns a dictionary that gets added to the template context. Each context processor must return a dictionary.

(Emphasis mine).

You ought to look at writing a custom middleware instead. If anyone knows of a way to make a context processor do this I'd like to know.

Manoj Govindan
A: 

You cannot do this with a Django context processors: they only have access to the request object, not the existing template context that their result is added to.

Storing the city in the sessions sounds all right, if that's what you want. Templates would be responsible for any further defaulting; if you need something fancy, you might want to look at wrapping it in a reusable custom template tag.

Piet Delport
A: 

You cannot access the current context from within a context processor, and I guess also a middleware wouldn't be the right solution for you. Maybe it would make sense to create your own template render function that you use in your views and you always pass it the context and the current request and put the functionality you want in it and render the template at the end with the usual rendering functions django provides you!

lazerscience