Dynamic variables in Django base.html

I have an application that uses flatpages and other constructs that do not accept a request object. This causes problems in base.html. Here is a simple example.

If I wanted something like "Welcome {{request.user.username}}!" at the top of each page, what's the best way to do this?

+4
source share
2 answers

Flat pages use RequestContext in rendering templates . Here is a bit more about RequestContext . Suffice it to say that you should be able to write a Context Processor to add request.user to the context of each template. Something like that:

 def user(request): """A context processor that adds the user to template context""" return { 'user': request.user } 

What would you then add to an existing TEMPLATE_CONTEXT_PROCESSORS in settings.py:

 TEMPLATE_CONTEXT_PROCESSORS = TEMPLATE_CONTEXT_PROCESSORS + ( 'context_processors.user', ) 

You just need to make sure that all of your views bind RequestContext with their templates:

 return render_to_response('my_template.html', my_data_dictionary, context_instance=RequestContext(request)) 

Here's a good read on Context Processors. This is a very useful feature.

+5
source

All Articles