Four new shortcuts
We've added four new shortcuts that'll help you use even less code in your Django applications. Each shortcut is designed to express a common idiom in a single line of code.
The first idiom is something like this:
from django.core import template, template_loader
from django.utils.httpwrappers import HttpResponse
def foo_view(request):
t = template_loader.get_template('foo/foo_detail')
c = template.Context({'foo': 'bar'})
return HttpResponse(t.render(c))
If you're a Django developer, you've probably used something very similar to that: Load a template, fill it with a context and return an HttpResponse with the rendered template. Because that's so common, we've added a shortcut: render_to_response(). Here's the same code, rewritten:
from django.core.extensions import render_to_response
def foo_view(request):
return render_to_response('foo/foo_detail', {'foo': 'bar'})
We've also added render_to_string(), which does the same thing as render_to_response() but returns a string instead of an HttpResponse.
Here's a second idiom that's quite common in Django code:
from django.core.exceptions import Http404
from django.models.bar import foos
try:
f = foos.get_object(some_field__exact=some_lookup)
except foos.FooDoesNotExist:
raise Http404
We've introduced get_object_or_404() to reduce this common case to a single line. Here's the same code, rewritten:
from django.core.extensions import get_object_or_404 from django.models.bar import foos f = get_object_or_404(foos, some_field__exact=some_lookup)
There's also a get_list_or_404(), which works the same way but uses get_list() instead of get_object().
We've updated the documentation to use this new method in examples.
Finally, in both of these examples, old code (writing things out the long way) will still work.
Posted by Adrian Holovaty on September 24, 2005
Comments
Bjorn August 23, 2006 at 10:47 p.m.
Http404 is now in django.http, not django.core.exceptions
Ludvig Ericson January 7, 2007 at 10:47 p.m.
Is there any better documentation on render_to_response()?
I googled for it and ended up here.
Ludvig Ericson January 7, 2007 at 11:09 p.m.
In a reply to myself and others whom might have ended up here,
django.shortcuts.render_to_response() is but a mere wrapper around django.template.loader.render_to_string and only takes a template name (filename, database template name, et cetera), a dictionary and a context_instance. The two latter arguments default to None.
stp2007 April 5, 2007 at 12:28 p.m.
from django.template.loader import render_to_string
If you wish to use render_to_string()
llumi July 10, 2007 at 3:50 p.m.
core/extensions.py is no more.
render_to_response can be found in django.shortcuts:
from django.shortcuts import render_to_response
Comments are closed
To prevent spam, comments are no longer allowed after sixty days.


dashinho October 7, 2005 at 12:56 p.m.
nice!