pythonpython-3.xdjangodjango-viewspython-class

What are the advantages of class-based views compared to function-based views?


I always use FBVs (Function Based Views) when creating a django app because it's very easy to handle. But most developers said that it's better to use CBVs (Class Based Views) and use only FBVs if it is complicated views that would be a pain to implement with CBVs.

Why? What are the advantages of using CBVs?


Solution

  • 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.