Graham King

Solvitas perambulum

Django class-based views are easy

Summary
Since Django version 1.3, you can use class-based views for handling requests. To create a class-based view, import `View` from `django.views.generic.base` and `HttpResponse` from `django.http`. Define a class inheriting from `View` and override the `dispatch` method to return a response. In `urls.py`, include your view using the `as_view` method, which makes the view thread-safe by creating a new instance each time it's called. Rather than overriding `dispatch`, you can use the `get` and `post` methods for handling specific HTTP methods. Although class-based generic views are available, you aren't restricted to using them and can create custom views as needed.

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

views.py

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')

urls.py

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.