Class Based vs Function Based Views - Which One is Better to Use in Django?
Last Updated :
25 Sep, 2024
Django...We all know the popularity of this python framework all over the world. This framework has made life easier for developers. It has become easier for developers to build a full-fledged web application in Django. If you're an experienced Django developer then surely you might have been aware of the flow of the project. How things run in the boilerplate of Django and how data gets rendered to the user.

Django works on the MVT concept we mainly work on two types of views in it... class-based views and function-based views. If you're new to the Django framework then surely you might have been using FBVs (Function Based Views).
Initially, Django started with the Function Based Views but later Django added the concept of class-based views to avoid the redundancy of code in the boilerplate. It is a debate among developers which one is better to use in Django... class-based views or function-based views? Today in this blog we are going to discuss this topic in-depth to get to know the pros and cons of both of the views.
You can accomplish your task using both of them. Some tasks can be best implemented using CBVs and some of them can be implemented in FBVs. Django views have mainly three requirements...
- They are callable. You can write the views either using function-based or class-based. While using CBVs you inherit the method as_view() that uses the dispatch() method to call the method that is appropriate depending on the HTTP verb (get, post), etc.
- As a first positional argument, Django views should accept HttpRequest.
- It should return the HttpResponse object, or it should raise an exception.
Now let's compare both of the views and see the pros and cons of both of them.
1. Function-Based Views
Function-based views are good for beginners. It is very easy to understand in comparison to class-based views. Initially when you want to focus on core fundamentals, using the function-based views gives the advantage to understand it. Let's discuss some pros and cons of it.
Pros:
- Easy to read, understand and implement.
- Explicit code flow
- Straightforward usage of decorators.
- Good for the specialized functionality.
Cons:
- Code redundancy and hard to extend
- Conditional branching will be used to handle HTTP methods.
As we have discussed function-based views are easy to understand but due to the code redundancy in a large Django project, you will find similar kinds of functions in the views. You will find a similar kind of code is repeated unnecessarily.
Here is an example of a function-based view...
Python
def example_create_view(request, pk):
template_name = 'form.html'
form_class = FormExample
form = form_class
if request.method == 'POST':
form = form_class(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('list-view'))
return render(request, template_name, {'form': form})
All the above cons of FBVs you won't find in class-based views. You won't have to write the same code over and over in your boilerplate.
2. Class-Based Views
Class-based views are the alternatives of function-based views. It is implemented in the projects as Python objects instead of functions. Class-based views don't replace function-based views, but they do have certain advantages over function-based views. Class-based views take care of basic functionalities such as deleting an item or add an item.
Using the class-based view is not easy if you're a beginner. You will have to go through the documentation, and you will have to study it properly. Once you understand the function-based view in Django and your concepts are clear, you can move to the class-based views. Let's discuss the class-based views in detail.
Pros
- The most significant advantage of the class-based view is inheritance. In the class-based view, you can inherit another class, and it can be modified for the different use cases.
- It helps you in following the DRY principle. You won't have to write the same code over and over in your boilerplate. Code reusability is possible in class-based views.
- You can extend class-based views, and you can add more functionalities using Mixins.
- Another advantage of using a class-based view is code structuring. In class-based views, you can use different class instance methods (instead of conditional branching statements inside function-based views) to generate different HTTP requests.
- Built-in generic class-based views.
Cons
- Complex to implement and harder to read
- Implicit code flow.
- Extra import or method override required in view decorators.
Below is an example of a class-based view...
Python
class MyCreateView(View):
template_name = 'form.html'
form_class = MyForm
def get(self, request, *args, **kwargs):
form = self.form_class
return render(request, template_name, {'form': form})
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
form.save()
return HttpResonseRedirect(reverse('list-view'))
else:
return render(request, self.template_name, {'form': form})
We have a little abstraction and method as_view() is calling the dispatch() to determine which class method needs to be executed, depending on the HTTP request. as_view() let you override the class attributes in your URLs confs. You can do something like the below...
Python
urlpatterns = [
url(r'^new/$', MyCreateView.as_view(), name='original-create-view')
url(r'^new_two/$', MyCreateView.as_view(template_name='other_form.html',
form_class='MyOtherForm'), name='modified-create-view')
]
Once you start using the Django generic class-based views, you will be able to over-write the helper method like get_form_class and get_template_names. You can insert the additional logic at these points instead of just overriding the class attribute.
One of the good examples of it is...ModelFormMixin. form_valid method is overridden. With the updated value stored in self.object() form_valid method is overridden.
3. Django Generic Class-Based View
Creating a new object, form handling, list views, pagination, archive views all these things are the common use cases in a Web application. It comes in Django core, you can implement them from the module django.views.generic. Generic class-based views are a great choice to perform all these tasks. It speeds up the development process.
Django provides a set of views, mixins, and generic class-based views. Taking the advantage of it you can solve the most common tasks in web development.
The main goal is not to reduce the boilerplate. It saves you from writing the same code again and again. Modify MyCreateView to inherit from django.views.generic.CreateView.
Python
from django.views.generic import CreateView
class MyCreateView(CreateView):
model = MyModel
form_class = MyForm
You might be thinking that where all the code disappears. The answer is that it's all in django.views.generic.CreateView. You get a lot of functionality and shortcuts when you inherit from CreateView. You also buy into a sort of 'convention over configuration.' style arrangement. Let's discuss few more details...
By default template should reside in /<modelname>/<modelname>_form.html. You can change it by setting the class attribute template_name and template_name_suffix.
- We also need to declare the model and form_class attributes. Methods you inherit from CreateView rely on them.
- You will have to declare success_url as a class attribute on the view or you will have to specify get_absolute_url() in the model. This is important for the view in your boilerplate else the view won't know where to redirect to following a successful form submission.
- Define the fields in your form or specify the fields class attribute on the view. Here in this example, you can choose to do the latter.
Look at the example given below to check how it will look like.
Python
from django import forms
from . models import MyModel
class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
fields = ['name', 'description']
Conclusion
It is still a debate among developers that which one is good to use. Class-based views or function-based views? We have discussed the pros and cons for both of them but it totally depends on the context and the needs. We have mentioned that class-based views don't replace function-based views. In some cases, function-based views are better and in some cases, class-based views are better.
In the implementation of the list view, you can get it working by subclassing the ListView and overriding the attributes. In a scenario where you need to perform the more complex operation, handling multiple forms at once, a function-based view will be a better choice for you.
Similar Reads
Django Tutorial | Learn Django Framework
Django, built with Python, is designed to help developers build secure, scalable, and feature-rich web applications quickly and efficiently. Whether you're a beginner looking to create your first dynamic website or an experienced developer aiming to enhance your skills, this tutorial will guide you
11 min read
Django view
Views In Django | Python
Django Views are one of the vital participants of the MVT Structure of Django. As per Django Documentation, A view function is a Python function that takes a Web request and returns a Web response. This response can be the HTML contents of a Web page, a redirect, a 404 error, an XML document, an ima
6 min read
Django Function Based Views
Django is a Python-based web framework which allows you to quickly create web application without all of the installation or dependency problems that you normally will find with other frameworks. Django is based on MVT (Model View Template) architecture and revolves around CRUD (Create, Retrieve, Up
7 min read
Django Class Based Views
Class-Based Views (CBVs) allow developers to handle HTTP requests in a structured and reusable way. With CBVs, different HTTP methods (like GET, POST) are handled as separate methods in a class, which helps with code organization and reusability.Advantages of CBVsSeparation of Logic: CBVs separate d
6 min read
Class Based vs Function Based Views - Which One is Better to Use in Django?
Django...We all know the popularity of this python framework all over the world. This framework has made life easier for developers. It has become easier for developers to build a full-fledged web application in Django. If you're an experienced Django developer then surely you might have been aware
7 min read
Django Templates
Templates are the third and most important part of Django's MVT Structure. A Django template is basically an HTML file that can also include CSS and JavaScript. The Django framework uses these templates to dynamically generate web pages that users interact with. Since Django primarily handles the ba
7 min read
Django Static File
Static Files such as Images, CSS, or JS files are often loaded via a different app in production websites to avoid loading multiple stuff from the same server. This article revolves around, how you can set up the static app in Django and server Static Files from the same.Create and Activate the Virt
3 min read
Django Model
Django Models
A Django model is the built-in feature that Django uses to create tables, their fields, and various constraints. In short, Django Models is the SQL Database one uses with Django. SQL (Structured Query Language) is complex and involves a lot of different queries for creating, deleting, updating, or a
10 min read
Django model data types and fields list
Django models represent the structure of your database tables, and fields are the core components of those models. Fields define the type of data each database column can hold and how it should behave. This artcle covers all major Django model field types and their usage.Defining Fields in a ModelEa
4 min read
Built-in Field Validations - Django Models
Built-in Field Validations in Django models are the default validations that come predefined to all Django fields. Every field comes in with built-in validations from Django validators. For example, IntegerField comes with built-in validation that it can only store integer values and that too in a p
3 min read
How to use User model in Django?
The Djangoâs built-in authentication system is great. For the most part we can use it out-of-the-box, saving a lot of development and testing effort. It fits most of the use cases and is very safe. But sometimes we need to do some fine adjustment so to fit our Web application. Commonly we want to st
3 min read
Meta Class in Models - Django
Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel. Itâs free and open source. D
3 min read
get_object_or_404 method in Django Models
Some functions are hard as well as boring to code each and every time. But Django users don't have to worry about that because Django has some awesome built-in functions to make our work easy and enjoyable. Let's discuss get_object_or_404() here. What is get_object_or_404 in Django?get_object_or_404
2 min read
Django Admin Interface - Python
Prerequisites: Django Introduction and Installation Creating a ProjectThe Django Admin Interface is one of the most powerful features of the Django framework. It provides a ready-to-use interface for managing project data through models, allowing developers and site administrators to perform Create,
3 min read
More topics on Django
Handling Ajax request in Django
AJAX (Asynchronous JavaScript and XML) is a web development technique that allows a web page to communicate with the server without reloading the entire page. In Django, AJAX is commonly used to enhance user experience by sending and receiving data in the background using JavaScript (or libraries li
3 min read
Python | User groups with Custom permissions in Django
Let's consider a trip booking service, how they work with different plans and packages. There is a list of product which subscriber gets on subscribing to different packages, provided by the company. Generally, the idea they follow is the level-wise distribution of different products. Let's see the
4 min read
Django Admin Interface - Python
Prerequisites: Django Introduction and Installation Creating a ProjectThe Django Admin Interface is one of the most powerful features of the Django framework. It provides a ready-to-use interface for managing project data through models, allowing developers and site administrators to perform Create,
3 min read
Python | Extending and customizing django-allauth
Prerequisite: Django-allauth setup and Configuration Let's deal with customizing django-allauth signup forms, and intervening in registration flow to add custom processes and validations. Extending the Signup Form or adding custom fields in Django-allauth: One of the most common queries about allaut
4 min read
Django - Dealing with Unapplied Migration Warnings
Django is a powerful web framework that provides a clean, reusable architecture to build robust applications quickly. It embraces the DRY (Don't Repeat Yourself) principle, allowing developers to write minimal, efficient code.Create and setup a Django project:Prerequisite: Django - Creating projectA
2 min read
Sessions framework using django - Python
Django sessions let us store data for each user across different pages, even if theyâre not logged in. The data is saved on the server and a small cookie (sessionid) is used to keep track of the user.A session stores information about a site visitor for the duration of their visit (and optionally be
3 min read
Django Sign Up and login with confirmation Email | Python
Django provides a built-in authentication system that handles users, login, logout, and registration. In this article, we will implement a user registration and login system with email confirmation using Django and django-crispy-forms for elegant form rendering.Install crispy forms using the termina
7 min read