Friday, November 11, 2011

Django - Context Processors

In some occasions we may need information available to each template, like the user properties, the session settings, or an special variable.

What we could do is to add all this information to the response dictionary. However, it would contradict the DRY principle of Django.

A good approach is to use a customized Context Processor, which will add to the dictionary the returned variables of the function.

Specifically, the modifications we must do can be the following:

  • Define the Context Processor function, like for example:
def context_processor_function(request):
return {'additional_values': ['a','b','c']}

  • Load the function inside the TEMPLATE_CONTEXT_PROCESSORS variable of the
TEMPLATE_CONTEXT_PROCESSORS = ("django.core.context_processors.auth",
  • Use the variables inside the templates like any other variables of the dictionary
For more complete information, this links are useful: