[Django]-How to pass common dictionary data to every page in django


It blows me away how common this is. You want to use context processors my friend!

Very easy to create, like so:

def messagenumber_processor(request):
   return {'messagenumber': 5}

Since messagenumber is a dynamic variable based on the User, you could pull data from the database by fetching from request.user as you have full access to request within each context processor.

Then, add that to your TEMPLATE_CONTEXT_PROCESSORS within settings.py and you’re all set 🙂 You can do any form of database operation or other logic within the context processor as well, try it out!



Just to save someone’s time if new to django


TEMPLATE_CONTEXT_PROCESSORS = ("django.contrib.auth.context_processors.auth",

in home application, create a python file called context_processor.py

in the context_processor.py add a function like this:

def remote_ip(request):
  return {'remote_ip': request.META['REMOTE_ADDR']}

use it in the templates like {{ remote_ip }}


Write your own function to handle it.

def render_with_message_number(template, message_number, request):
    return render_to_response(template, dict(messagenumber=message_number),

And don’t shadow dict.

Leave a comment