Wednesday, February 15, 2012

Django Class Based Views Tutorial -- why I like them!

With the release of Django 1.3 developers can use class based views in addition to the function based views.  Django includes some generic prebuilt views that help to solve some basic problems.  Although they are a great starting point at some point you will probably find yourself having to write a custom class based view.  I hope to clearly explain how that is done.

What are they?

Most of the other functionality in django is already class based: models, forms, middleware.  For this reason views have always kind of stuck out.  They are function based. maps to one function.  That function takes a request as a parameter and must return a response object.  Classed based views applies the same oo concepts that are available in other parts of the framework to views.

Why use them?

A common scenario is having a page with a form.  A GET request renders the form and a POST request processes the form.  Although these two processes often share the same url they are very different.  I never have liked cramming these into one function.  

def form(request):
  if request.method == 'GET':
    return render_to_response('the_form_template.html')
  elif request.method == 'POST':
    # do some processing for the form
    # return redirect if successful

Often times I have found myself with some fairly complicated things taking place inside either one of these conditionals.  Code can grow difficult to read, with lots of nested conditionals.  Readability is just a preference of mine and might not bother everyone.   What bothers me the most is these are separate processes that just so happen to share a url.  That does not mean they should share a function though.  Class Based Views solves this problem.  They recognize that these are 2 sides of the same coin but can present them in a more readable way while keeping CRUD operations straight forward.  Class Based Views will automatically call the method associated with the request. Now using new Class Based Views:

from django.views.generic.base import View, TemplateResponseMixin
class TestView(View, TemplateResponseMixin):
  def get(self, request):
    self.template_name = 'the_form_template.html'
    # or you can instantiate your form and render with
    # a template as normal, then there would be no need for
    # the TemplateResponseMixin

  def post(self, request):
    # process the form and redirect.

Additionally, in there is a small change, instead of putting in the location of the function in patterns such as (r'^yourregex/$', '') you import your class

from myproject.myapp.views import TestView
(r'^yourregext/$', TestView.as_view())

If someone makes a request that is not supported django returns a 405 error.

What to use them for?

Whenever I have a url that does different things for different request methods I like to use ClassBased Views. I also use them when I have common tasks to do each request.  For a while I was finding that I had to write a lot of csv download functions, all of them would go something like: 1) validate input, 2)get data, 3) render data as csv.
I found that this was cleanly implemented by creating a generic CSVView.  Every time I had a different download to do I subclassed it and implemented the get_data method appropriately.

For reference django has some great documentation on their Generic Views,  but is lacking in documentation on Class Based Views.  The best source of information on them right now is the source code, easily accessible on github,


  1. This article is very straight forward and informative. Thank you for posting it.