Igor Sobreira

Replacing render_to_response with direct_to_template in Django

Update: September 3, 2012

A render() was introduced on Django 1.3 to use RequestContext by default

You certainly have already used render_to_response to render your templates, it's a very convenient shortcut:

from django.shortcuts import render_to_response

def myview(request):
    ...
    return render_to_response('template.html', {'foo': ['one', 'two']})

At least until you need to use context processors, then you start writing code like this

from django.shortcuts import render_to_response
from django.template import RequestContext

def myview(request):
    ...
    return render_to_response('template.html', 
            {'foo': ['one', 'two']},
            context_instance=RequestContext(request))

this context_instance argument is the boilerplate code you will always need to make context processors work. I think it's too much typing, and I'm lazy, so I prefer to use the direct_to_template generic view:

from django.views.generic.simple import direct_to_template

def myview(request):
    ...
    return direct_to_template(request, 'template.html', 
            {'foo': ['one', 'two']})

You don't need the context_instance argument anymore, and you save one import.

But! There is one simple detail when passing extra context to this view, if a value in your dict is a callable, it will call and pass the result to template. It can be useful, but is something to keep in mind, if you're trying to pass a callable to template.

Read the source code to understand how it works.

blog comments powered by Disqus

My name is Igor Sobreira and is my website. I'm a software developer working at Real Geeks. I currently live in Hawaii doing the two things that I like most: windsurfing and writing software.

See more about me and get in touch.