This appendix follows on from Chapter 15, in which we implemented Django forms for validation and refactored our views. By the end of that chapter, our views were still using functions.
The new shiny in the Django world, however, is class-based views. In this appendix, we’ll refactor our application to use them instead of view functions. More specifically, we’ll have a go at using class-based generic views.
There’s a difference between class-based views and class-based generic views. Class-based views (CBVs) are just another way of defining view functions. They make few assumptions about what your views will do, and they offer one main advantage over view functions, which is that they can be subclassed. This comes, arguably, at the expense of being less readable than traditional function-based views. The main use case for plain class-based views is when you have several views that reuse the same logic. We want to obey the DRY principle. With function-based views, you would use helper functions or decorators. The theory is that using a class structure may give you a more elegant solution.
Class-based generic views (CBGVs) are class-based views that attempt to provide
ready-made solutions to common use cases: fetching an object from the
database and passing it to a template, fetching a list of objects, saving
user input from a POST request using a
ModelForm, and so on. These sound very much like our use cases, but as ...