I believe that one of its main advantages is the elimination of repeated code.
CBVs are, from my point of view, more efficient than function-based views because they reduce the code needed to produce the expected result. This reduction not only adds clarity to the code, it also facilitates understanding and maintenance of the code.
The use of class-based views has a positive impact on other elements of the application by allowing a better structure of models and URL patterns, for example.
To illustrate the advantages of class-based views, I add a real example.
In a document control application, the document model has the get_absolute_url
method that looks like this:
def get_absolute_url(self):
return reverse('detalle', kwargs={'pk': self.id})
And in the file urls.py
a a search pattern related to the previous method:
url(r'^(?P<pk>\d+)/control$', DetalleDocumento.as_view(), name='detalle'),
With these two elements, the view based on the respective class is reduced to the following:
class DetalleDocumento(DetailView):
model = Documento
template_name = "docs/detalle.html"
And template_name
, by the way, is an optional parameter.
This is the main advantage of the CBV: the code is reduced to its minimum expression, but does not lose legibility or efficiency. In addition CBVs work in most situations, so Django's DRY principle becomes apparent.