Search code examples
djangodjango-urlsdjango-context

Django Context Processors: Is it possible to access current context in ContextProcessor?


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 ?


Solution

  • 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!