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 setting.py:
TEMPLATE_CONTEXT_PROCESSORS = ("django.core.context_processors.auth",
...
"path_to_context_processor_function.context_processor_function
",)
  • Use the variables inside the templates like any other variables of the dictionary
For more complete information, this links are useful:

http://www.b-list.org/weblog/2006/jun/14/django-tips-template-context-processors/

https://docs.djangoproject.com/en/1.1/ref/settings/#std:setting-TEMPLATE_CONTEXT_PROCESSORS

http://stackoverflow.com/questions/335231/in-django-is-it-possible-to-access-the-current-user-session-from-within-a-custo