views:

32

answers:

2

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

+1  A: 

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),
        context_instance=RequestContext(request))

And don't shadow dict.

Ignacio Vazquez-Abrams
+3  A: 

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!

Bartek
Two notes:1) You'll need to have django.contrib.auth.middleware.AuthenticationMiddleware in your MIDDLEWARE_CLASSES setting in order for request.user to work.2) Only templates rendered with django.template.RequestContext instances as context will have context processors applied.
Joseph Spiros
thanks, a couple of more questions. *)I can put this method in any where (in any my view files)?*)Adding this processor like 'myproject.myapp.myview.messagenumber_processor'?and*) How to call this data in template ? request.messagenumber_processor?
xlione
@Joseph Valid points, which are stated in the links I posted, but thanks!@xlione You technically can put it anwyhere within your project, but it's recommended to place it in a `context_processors.py` for the application that these context processors will deal with. To call the data in your template, reference the dict you return in the context processor. E.g in my example if I put `{{ messagenumber }}` in my template, it would output `5` assuming I linked up my context processor all correctly.
Bartek
thanks again! it works like a charm!
xlione