Class-based generic views (anti)patterns - Bruno Renié

Tags: django, djangocon

Class based views (CBV) were new in django 1.3, they’re better in 1.4. Surprising to him a core developer said last week that CBVs are a mistake.

Regarding deprecation: only function based generic views (build into django) are deprecated. Function based views as such will stay.

Classes in django are normally instantiated in the normal python way. CBVs have a bit of a problem that they must not be re-used over multiple requests (the actual problem is a bit hard to explain). For that, you must use .as_view() in your URL config.

Class based views are a bit hard to get into. Hard to understand. There are sites like to help you, though. He likes them a lot now. Some usage tips:

  • Use your just for handling URLs. Don’t use decorators in there. And use a CBV decorator trick.

  • The inheritance and class mixin tree of CBVs is quite elaborate. To keep yourself sane, don’t overwrite functionality but only add.

Areas where CBVs shine:

  • Form processing. Instead of the regular if request.POST, the CBV form handler that django gives you is way handier and clearer.

  • Nested navigation. You can make a class inheritance and every class can add something to the context.

  • You can easily drop in features, like pagination. Only add it if you need it.

Another example: django-registration. It is great, but you might not be using contrib.auth. Or you might want to use more template variables. Or you want to send an SMS instead of an email on success. So he wrote django-le-social with class based views.

Settings. It is easy to add one. But, does it have to be that global? Can it be a local switch? In such a case, a variable in your CBV might be enough. If necessary, you can subclass or overwrite it. In the same way, he used success_url and error_url variables in his django-le-social project. Again, easy to customize.

Don’t use CBVs for everything, though.

  • CBVs do more than function based views. More behind the scenes, that is. So you might need to be aware of implementation details. So sometimes a function based view is easier.

  • CBVs for the generic views: more power, but less simplicity. So you might want to watch out.

Good tip: don’t depend too much on the various generic CBVs that Django provides. Feel free to make your own base classes!

(That last point was also made during the questions. The docs should emphasize making your own CBVs more, the current docs mostly talk about the generic views).

Photo & Video Sharing by SmugMug logo

About me

My name is Reinout van Rees and I work a lot with Python (programming language) and Django (website framework). I live in The Netherlands and I'm happily married to Annie van Rees-Kooiman.

Weblog feeds

Most of my website content is in my weblog. You can keep up to date by subscribing to the automatic feeds (for instance with Google reader):