Depending on the project you are working on, you might want to access one or more template variables across all your templates like the User object. If you are making news or blog project, one example would be navigation bar item, say a category list.
You might be tempted to pass the category list from your views or create a template tag for that; but that just violate the Django’s DRY principle. So the best way would be through custom context processor. Writing your own is actually very easy.
1. Writing the context processor function.
You can put this function anywhere in your project. My preference is to place this code inside a context_processors.py file under the related app.
Note: Each context processor must return a dictionary and takes only one arguement, HttpRequest object.
2. Point it to your TEMPLATE_CONTEXT_PROCESSORS in your settings.py file.
Now categories is available for use in all your templates.
Done!
Thanks man, that way is very easy to understand and to code. I just added it to my project and it worked perfectly, I needed to have a dynamic name in the base.html.
My only doubt is if I need to have all those others processors, I only added mine and .auth because it was giving me an error.
Thanks again!
thank you so much for this perfect example.
Exactly what I need it when I need it 🙂
Great man. This is so simple and works like a charm. Some people (e.g. http://www.b-list.org/weblog/2006/jun/14/django-tips-template-context-processors/) claim an extra context_instance is required. But that doesn’t seem to be true as your simple solution works fine. Maybe that more complicated solution is required for older django versions?
Very useful, thanks a lot!
Thx for this, helped me very much.
Just one update: “TEMPLATE_CONTEXT_PROCESSORS” are deprecated. Insert your TEMPLATE_CONTEXT_PROCESSORS in TEMPLATES
https://docs.djangoproject.com/en/1.11/ref/templates/upgrading/
thanks! really it works without any problem. I am using Django2.0
thx from russia