Django common dictionary available to templates

By | May 11, 2011

We need to leverage TEMPLATE_CONTEXT_PROCESSORS, the following example uses the “home” application

  1. add this to settings.py
    TEMPLATE_CONTEXT_PROCESSORS = ("django.contrib.auth.context_processors.auth", "django.core.context_processors.debug", "django.core.context_processors.i18n", "django.core.context_processors.media", "django.core.context_processors.static", "django.contrib.messages.context_processors.messages", "home.context_processor.remote_ip")
  2. in home application, create a python file called context_processor.py
  3. in the context_processor.py add a function like this:
    def remote_ip(request):
    return {'remote_ip': request.META['REMOTE_ADDR']}
  4. for any templates needs to use this processor need to render the template like this
    vars = {}
    return render_to_response('home.html', vars, context_instance=RequestContext(request))
  5. use it in the templates like {{ remote_ip }}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.