Class-Based Views(CBV) vs Function Based Views(FBV) in Django

Class-Based Views(CBV) vs Function Based Views(FBV) in Django

When exploring the views file in a Django project, it might seem difficult for a beginner to decide whether to use the Class-Based Views or the Function Based Views. In this article, I will try to deliver the differences between these two.

NOTE: For further part of the article CBVs: Class-Based Views & FBVs: Function-Based Views

The basic difference as anyone can guess is that CBVs are written using python class and FBVs are written using Python functions. At the core, they are doing quite the same job. One of the major differences that can help us choose which one to use is that in CBVs, we can inherit from another class, so it makes it easier for us at times when we have to write a code for a logic that has already been implanted in another class. For example, while creating a blog project, when we are creating a post detail view, we can inherit the logic from detail view, which in terms help us to minimize the code and makes the process a lot easier. Here's how you can do it :

# We will now inherit the Detail view to avoid writing extra code
class PostDetailView(DetailView):
    model=blog
    template_name='blogdetail.html'

The same view created using FBVs will look like this:

def BlogDetailView(request,id):
    context={"data":blog.objects.get(id=id)}
    return render(request,"blogdetail.html",context)

So in conclusion CBVs have the ability to inherit the other classes, which in turn helps in not having to write extra code whereas in FBVs we have to write all the code as there is no inheritance.

Now moving on, FBVs are very easy to read and to get implemented as the process is quite simple, the function gets a request and outputs a response. CBVs can sometimes be hard to read as there are a lot of built-ins.

In the end, there's nothing better or worse, it just depends on the scenario you are in, if you have a large codebase and are quite sure that a lot of code is to be repeated then you can use CBVs as they help in code, meanwhile if you have to write complex views(i.e very customized) then using FBVs is the way for you.

That's all for the article. I hope that it would have helped you clear the confusion between CBVs and FBVs. Please comment with your valuable suggestions and feedback. In case you want to connect with me, follow the links below:

LinkedIn | GitHub | Twitter