Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass common dictionary data to every page in django

I have a common data {the logged-in user's message number) to display on every page. I can simply pass to template as

dict={'messagenumber':5}
return render_to_response('template.html',dict,context_instance=RequestContext(request))

But it looks tedious if i have this dict data pass to very page. Is there an easier way to pass common data to every page?

Thanks

like image 600
icn Avatar asked Jul 11 '10 02:07

icn


2 Answers

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!

like image 40
Bartek Avatar answered Oct 12 '22 02:10

Bartek


Just to save someone's time if new to django

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")

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 }}

like image 51
James Lin Avatar answered Oct 12 '22 00:10

James Lin