Four new shortcuts

Posted by Adrian Holovaty on Sept. 24, 2005

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.

Back to Top