Class Based Views VS Function Based Views

The single most significant advantage is inheritance. On a large project it’s likely that you will have lots of similar views. Rather than write the same code again and again, you can simply have your views inherit from a base view.

Also django ships with a collection of generic view classes that can be used to do some of the most common tasks. For example the DetailView class is used to pass a single object from one of your models, render it with a template and return the http response. You can plug it straight into your url conf..

url(r'^author/(?P<pk>\d+)/$', DetailView.as_view(model=Author)),

Or you could extend it with custom functionality

class SpecialDetailView(DetailView):
    model = Author
    def get_context_data(self, *args, **kwargs):
        context = super(SpecialDetailView, self).get_context_data(*args, **kwargs)
        context['books'] = Book.objects.filter(popular=True)
        return context

Now your template will be passed a collection of book objects for rendering.

A nice place to start with this is having a good read of the docs (Django 4.0+).

Update

ccbv.co.uk has comprehensive and easy to use information about the class based views you already have available to you.

Leave a Comment