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:

1 comment:

  1. Hello Dude,

    As it turns out, Django provides an extremely easy way to do this. Every time you render a template, you give it a context, this is a dictionary-like object whose keys are variable names and whose values are the values of the variables. When you render a template with a given context, every key in the context dictionary becomes a variable in the template that you can access and use. Thanks for sharing it.....

    Extract Web Data