Class Based Views VS Function Based Views

Some views are best implemented as CBVs, and others are best implemented as FBVs.

If you aren’t sure which method to choose, see the following chart:

enter image description here


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.


When I started with DJango I never used CBVs because of their learning curve and a bit complex structure. Fast forward over two years, I use FBVs only at few places. Where I am sure the code will be really simple and is going to stay simple.

Major benefit of CBVs and Multiple Inheritence that comes along with them is that I can completely avoid writing signals, helper methods and copy paste code. Especially in the cases where the app does much more than basic CRUD operations. Views with multiple inheritance are multiple times easier to debug that a code with signals and helper methods, especially if it is an unknown code base.

Apart from Multiple inheritence CBVs by provide different methods to do dispatching, retrieving templates, handling different request types, passing template context variables, validating forms, and much more out of the box. These make code modular and hence maintainable.