Django render_to_response

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)

5 Responses to “Django render_to_response”


  1. 1 Daniel Swarbrick January 16, 2010 at 7:34 am

    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.

  2. 3 Vinicius Mendes January 16, 2010 at 9:23 am

    Very nice hint. I actually always use the direct_to_template generic view instead of the render_to_response.

  3. 4 John M January 17, 2010 at 12:38 pm

    Why not just use direct_to_template, doesn’t that use the context?


Leave a comment