May 20, 2011

Django class-based views are easy

Posted in Software at 16:49 by graham

Since version 1.3, Django has class-based views built-in. Here’s how to do it:

from django.views.generic.base import View
from django.http import HttpResponse

class MyView(View):
    def dispatch(self, request, *args, **kwargs):
        return HttpResponse('Hello World!', mimetype='text/plain')

from myproj.myapp.views import MyView

 urlpatterns = patterns('',
      url(r'^$', MyView.as_view()),

Tell me more

Docs are here: Official Django class based views documentation

Internally the as_view method creates a new instance of your class (thereby making things thread-safe), and passes the __init__ method anything you passed to as_view.

Instead of over-riding dispatch you might prefer to use the get and post methods, which get called when you’d expect.

What had me confused initially, is that they are refered to as class-based generic views. Yes the generic views are implemented like this, and you may benefit from sub-classing one of those instead of the bare-bones View, but you don’t have to.