APPENDIX B
Django Class-Based Views
This appendix follows on from
Chapter 12, 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.
Class-Based Generic Views
There’s a difference between class-based views and class-based
generic
views. Class-
based views are just another way of defining view functions. Theymake fewassumptions
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 decora‐
tors. The theory is that using a class structure may give you a more elegant solution.
Class-based
generic
views 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 we’ll soon see,
the devil is in the detail.
I should say at this point that I’ve not used either kind of class-based views much. I can
definitely see the sense in them, and there are potentially many use cases in Django apps
where CBGVs would fit in perfectly. However, as soon as your use case is slightly outside
the basics—as soon as you have more than one model you want to use, for example—I
413