In a new Django project, should I use Class-based or Function-based views?

django, python

Solution

This is a matter of opinion, personally I disagree with Luke Plant on this and I've fallen in love with `Class Based Views`. I think much of the resistance from the Django community to eagerly adopt them stemmed from the fact that they couldn't easily see how they worked (the implementation uses a lot of Mixins and can be hard to follow) and the documentation was lacking, that and I think there was a lot of misunderstanding about Generic CBV's and plain CBV's. (for a long time when ever you Googled “django class based views” the first results were about generic views)

Now the documentation is getting much better and the tools available to help understand them are great (see ccbv.co.uk or pudb).

I suggest learning and using `Class Based Views` for the same reasons people suggest OOP, it reduces code repetition and increases code reuse (inheritance, mixins)… in other words, it's DRY.

One more thing, it's worth checking out how other projects use `CBV`'s… one of my recent favourites is django-oscar, which uses them to good effect.

Problem

In a new Django project, I am just wondering whether to use Class-Based Views (CBV) or Function-Based Views (FBV). According to Django's documentation: Class-based views provide an alternative way to implement views as Python objects instead of functions. They do not replace function-based views, but have certain differences and advantages when compared to function-based views Which seems to contradict to python Zen 'There is only one way to do it' So, which is the better way? So far, I only see three possibilities: Always using FBV Which means not using generic views at all (as those are class-based since 1.5) Always using CBV: Which has certain problems with determination of request processing orders. See http://lukeplant.me.uk/blog/posts/djangos-cbvs-were-a-mistake/ I also think that building the whole class hierarchy is not good for the performance. In that case I also would ask myself, why FBV are not deprecated yet? Putting generic CBV into FBV, according to https://gist.github.com/spookylukey/2596285 which results in a lot of cruel boilerplate code Do you see any other ways, or does anyone know where the views are going?

Original source