It is important to see how django doesn’t automatically appends the context variables to the request object.
Say you want to access MEDIA_URL in your templates, using the following code will not work since the context is not created and it is not passed to the render_to_response function
def my_view(request): return render_to_response('my_template.html', my_data_dictionary)
The first solution is to build the context and pass it to the render_to_response function, like this:
def my_view(request): return render_to_response('my_template.html', my_data_dictionary, context_instance=RequestContext(request))
But, this is kind of repetitive and boring. So a django snippet was proposed for that in http://www.djangosnippets.org/snippets/3/
from django.shortcuts import render_to_response from django.template import RequestContext def render_response(req, *args, **kwargs): kwargs['context_instance'] = RequestContext(req) return render_to_response(*args, **kwargs)
That works, But django just implemented almost the same thing in generic views. So, the solution I prefer is using the direct_to_template generic view
def my_view(request): # View code here... return direct_to_tempalte(request, template_name='my_template.html', extra_context=some_dict)
I wouldn’t say they _just_ implemented direct_to_template. It’s been in the source since November 2005, and I’ve been using that method in my projects for at least two years. I’m surprised so many people overlook this shortcut.
Yes you are right, direct_to_template it’s been in the source for years. Thanks for the clarification.
Very nice hint. I actually always use the direct_to_template generic view instead of the render_to_response.
Why not just use direct_to_template, doesn’t that use the context?
Sure, That’s the point!!