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

拜拜、爱过 提交于 2019-12-05 02:20:35

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!

You can achieve this using TemplateResponse and TemplateResponse middleware.

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!