Sometimes when building a web application with Django, you have a common piece of information that is available at all the templates. Foe example, you may have a dynamically built tree menu appearing in multiple templates. It’s possible to achieve so by adding the data to the context of each template. But that goes against Django’s policy on code reuse. The right way to do that, is to use template context processors and ReuestContext objects.
The sections on Django official documentation are either too short or under misleading headings. So I’m trying to write this in a paint-by-numbers sort of way.
First, the template
Let’s suppose you have the following silly piece of HTML in each of your templates
Hello World! My name is {{name}}
Next, create a custom context processor
Under the directory of your Django application create a new file. Let’s name it ‘custom_context_processors.py’. This is your custom context processor, that will list a number of methods, each of which will have a HttpRequest object as parameter. Suppose you want to have a variable named ‘domain’ available at all template. Let’s add a method to the processor by that name:
define name(request): return {'name': 'Django Guru'}
Install the Context Processor
Open settings.py. Add the following line in the TEMPLATE_CONTEXT_PROCESSORS
'myapp.custom_context_processors.domain,'
Add the RequestContext
In your views.py, import the RequestContext module
from django.templates import RequestContext
Now when you render the template using render_to_response() method, a RequestContext object has to be added as the optional context_instance argument. The RequestContext object takes a HttpRequest object as a parameter
def my_view(request): #view code return redner_to_response('my_template.html', {'foo:bar'}, \ context_instance=RequestContext(request))
The variable {{name}} will now be available in my_template.html, without explicitly adding it in the template context. If you need to make it available in some_other_template.html, all you need to do is to pass the RequestContext object as the third parameter to render_to_reponse().
Hi,
is it possible that you mixed “name” and “domain” in your example?
I think franz is right, and also found some other small errors:
– “define” should be “def” in the first snippet
– in views.py it should be “from django.template” not “templates”
– in the last snippet “redner_to_response” should be “render_to_response” (well, this one is pure typo)
Please correct me if I am wrong with any of these.
A very useful post anyway, thanks!
bien charchita la weaíta
Thanks for the article, it’s very simple and useful. However there is a typo in:
from django.templates import RequestContext
it should be:
from django.template import RequestContext
Pingback: [Django]-Django – Show/hide urls in base html dependant on user group? - TheCodersCamp