In software development, be dry, and define data once. But, what if that data needs to be used in many places? This is the case with parts of a web page, for instance, that are common to many different pages. Django has a great mechanism for this: it is context processors.
You can define a context processor, containing within in the things that you would like to be present and available for use within the given context. There are two ways that I’ve found to include context processors: Per request or for all requests.
Pass the context processor into the request in your view.py:
1 2 3 4 5
That means that when the content_list.html template is loaded, all content_common variables will be available in that template context. Those variables are:
1 2 3 4 5 6 7 8 9
For All Requests
Sometimes you don’t have absolute control of all the views in your project (ie, plugins). So, what if you want to apply the context processor to those views as well? The best way that I’ve found is by including the context processor definition in the settings.py file:
1 2 3
Glory, glory, django.
Just make sure that you put the auth context processor in with the TEMPLATE_CONTEXT_PROCESSOR entries that you’re adding, otherwise you’ll get this message:
1 2 3