Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Cannot retrieve contributors at this time

62 lines (45 sloc) 1.308 kb

templatable_view decorator

This decorator is a simple, clean shortcut for not having to write the very verbose render_to_respone code in Django.

Instead of this:

def view(request):
    context = { }
    return render_to_response(template_name, context,  context_instance=RequestContext(request))

you can write:

@templatable_view(template_name)
def view(request):
    return { }

When the templatable_view decorator detects that a normal HttpResponse object has been returned, it won't touch it and pass it to the Django middleware.

Some other examples

  1. Defining a default dictionary. (Variables to be passed to the template, if the view doesn't return any of these.)
@templatable_view('app/template.html', { 'param1': 4, 'param2': 5 })
def view(request):
    return { ... }
  1. Returning a HttpResponse
@templatable_view('app/template.html')
def view(request):
    if condition:
        return HttpResponseRedirect(reverse('home'))
    else
        return {'form': form }
  1. Overriding the template in the view
@templatable_view('app/template.html')
def view(request):
    if condition:
        return  { ... }
    else:
        return  'app/other-template.html', { ... }
Jump to Line
Something went wrong with that request. Please try again.