Saturday, November 24, 2007

render_to_response()

render_to_response()

Because it’s such a common idiom to load a template, fill a Context and return an HttpResponse object with the result of the
rendered template, Django provides a shortcut that lets you do those things in one line of code. This shortcut is a function
called render_to_response(), which lives in the module django.shortcuts. Most of the time, you’ll be using render_to_response() rather than loading templates and creating Context and HttpResponse objects manually.

Here’s the ongoing current_datetime example rewritten to use render_to_response():

from django.shortcuts import render_to_response
import datetime
def current_datetime(request):
now = datetime.datetime.now()
return render_to_response('current_datetime.html', {'current_date': now})

What a difference! Let’s step through the code changes:
l We no longer have to import get_template, Template, Context or HttpResponse. Instead, we
import django.shortcuts.render_to_response. The import datetime remains.
l Within the current_datetime function, we still calculate now, but the template loading, context creation, template rendering
and HttpResponse creation is all taken care of by the render_to_response() call. Because render_to_response() returns
an HttpResponse object, we can simply return that value in the view.
The first argument to render_to_response() should be the name of the template to use, relative to your template directory. The
second argument, if given, should be a dictionary to use in creating a Context for that template. If you don’t provide a second
argument, render_to_response() will use an empty dictionary

1 comment:

strangethingintheland said...

appreciate the clear explanation.