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 CBVs
- Separation of Logic: CBVs separate different behaviors (GET, POST) into separate methods.
- Reusable Components: Common functionality can be factored out into reusable mixins or base classes.
- Built-in Generic Views: Django provides several built-in CBVs like CreateView, ListView, DetailView, etc., for common tasks.

- CreateView - create or add new entries in a table in the database.
- Retrieve Views - read, retrieve, search, or view existing entries as a list(ListView) or retrieve a particular entry in detail (DetailView)
- UpdateView - update or edit existing entries in a table in the database
- DeleteView - delete, deactivate, or remove existing entries in a table in the database
- FormView - render a form to template and handle data entered by user
Django Class Based Views CRUD Operations
Illustration of How to create and use CRUD views using an example, consider a project named "geeksforgeeks" having an app named "geeks".
Refer to the following articles to check how to create a project and an app in Django.
Let’s now see how to implement CRUD operations using CBVs in Django.
Step 1: Define the Model
The first step is to define the model in Django. For our example, let’s create a model named GeeksModel to store the title and description of a record.
In geeks/models.py:
Python
from django.db import models
class GeeksModel(models.Model):
title = models.CharField(max_length = 200)
description = models.TextField()
def __str__(self):
return self.title
Explanation:
- title: A CharField for the title of the record.
- description: A TextField for the description of the record.
Run the following commands to create and apply database migrations:
Python manage.py makemigrations
Python manage.py migrate
To make it easier to create and update GeeksModel instances, let’s create a ModelForm. This form automatically generates a form for the model’s fields.
In geeks/forms.py:
Python
from django import forms
from .models import GeeksModel
class GeeksForm(forms.ModelForm):
class Meta:
model = GeeksModel
fields = ["title", "description",]
Explanation:
- GeeksForm: A form class that generates a form for GeeksModel with fields title and description
Step 3: Create Class-Based Views
CreateView (For Creating Entries)
The CreateView class-based view provides the functionality to create new database records. We will use it to add new GeeksModel entries.
In geeks/views.py:
Python
from django.views.generic.edit import CreateView
from .models import GeeksModel
class GeeksCreate(CreateView):
model = GeeksModel
fields = ['title', 'description']
template_name = 'geeks/geeksmodel_form.html'
success_url = '/'
Explanation:
- model: Specifies the model that the view will work with.
- fields: Specifies the fields that will be displayed on the form.
- template_name: Points to the HTML template where the form will be rendered.
- success_url: Defines the URL to redirect to after successfully creating a new entry.
reate the corresponding template geeks/geeksmodel_form.html:
HTML
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit">
</form>
URL Mapping: In geeks/urls.py, map the GeeksCreate view:
Python
from django.urls import path
from .views import GeeksCreate
urlpatterns = [
path('create/', GeeksCreate.as_view(), name='geeks_create'),
]
Let's check what is there on "http://localhost:8000/"

To check complete implementation of Class based CreateView, visit Createview – Class Based Views Django.
ListView (For Retrieving Multiple Entries)
The ListView class-based view is used to retrieve and display a list of records.
In geeks/views.py:
Python
from django.views.generic.list import ListView
from .models import GeeksModel
class GeeksList(ListView):
model = GeeksModel
template_name = 'geeks/geeksmodel_list.html'
context_object_name = 'geeks_list'
Create the corresponding template geeks/geeksmodel_list.html:
HTML
<ul>
<!-- Iterate over object_list -->
{% for object in object_list %}
<!-- Display Objects -->
<li>{{ object.title }}</li>
<li>{{ object.description }}</li>
<hr/>
<!-- If object_list is empty -->
{% empty %}
<li>No objects yet.</li>
{% endfor %}
</ul>
URL Mapping: In geeks/urls.py, map the GeeksList view:
Python
from django.urls import path
from .views import GeeksList
urlpatterns = [
path('', GeeksList.as_view(), name='geeks_list'),
]
Let's check what is there on "http://localhost:8000/"

To check complete implementation of Class based ListView, visit ListView – Class Based Views Django
DetailView (For Retrieving a Single Entry)
The DetailView is used to display detailed information about a single record.
In geeks/views.py:
Python
from django.views.generic.detail import DetailView
from .models import GeeksModel
class GeeksDetailView(DetailView):
# specify the model to use
model = GeeksModel
Now create a url path to map the view. In geeks/urls.py,
Python
from django.urls import path
# importing views from views..py
from .views import GeeksDetailView
urlpatterns = [
# <pk> is identification for id field,
# slug can also be used
path('<pk>/', GeeksDetailView.as_view()),
]
Create a template in templates/geeks/geeksmodel_detail.html,
HTML
<h1>{{ object.title }}</h1>
<p>{{ object.description }}</p>
Let's check what is there on "http://localhost:8000/1/"

To check complete implementation of Class based DetailView, visit DetailView – Class Based Views Django
UpdateView (For Updating Entries)
The UpdateView allows you to edit an existing record.
In geeks/views.py:
Python
from django.views.generic.edit import UpdateView
from .models import GeeksModel
class GeeksUpdateView(UpdateView):
model = GeeksModel
fields = [
"title",
"description"
]
success_url ="/"
Now create a url path to map the view. In geeks/urls.py,
Python
from django.urls import path
from .views import GeeksUpdateView
urlpatterns = [
path('<pk>/update', GeeksUpdateView.as_view()),
]
Create a template in templates/geeks/geeksmodel_form.html,
HTML
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Save">
</form>
Let's check what is there on "http://localhost:8000/1/update/"

To check complete implementation of Class based UpdateView, visit UpdateView – Class Based Views Django.
DeleteView (For Deleting Entries)
The DeleteView allows you to delete a record from the database.
In geeks/views.py:
Python
from django.views.generic.edit import DeleteView
from .models import GeeksModel
class GeeksDeleteView(DeleteView):
model = GeeksModel
success_url ="/"
Now create a url path to map the view. In geeks/urls.py,
Python
from django.urls import path
from .views import GeeksDeleteView
urlpatterns = [
path('<pk>/delete/', GeeksDeleteView.as_view()),
]
Create a template in templates/geeks/geeksmodel_confirm_delete.html,
HTML
<form method="post">{% csrf_token %}
<p>Are you sure you want to delete "{{ object }}"?</p>
<input type="submit" value="Confirm">
</form>
Let's check what is there on "http://localhost:8000/1/delete"

To check complete implementation of Class based DeleteView, visit DeleteView – Class Based Views Django
The FormView is used to display and process forms. It provides a way to handle form submissions using CBVs.
In geeks/views.py:
Python
from django.views.generic.edit import FormView
from .forms import GeeksForm
class GeeksFormView(FormView):
form_class = GeeksForm
template_name = "geeks / geeksmodel_form.html"
success_url ="/thanks/"
Create a template for this view in geeks/geeksmodel_form.html,
HTML
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Save">
</form>
Map a url to this view in geeks/urls.py,
Python
from django.urls import path
from .views import GeeksFormView
urlpatterns = [
path('', GeeksFormView.as_view()),
]
Now visit "http://127.0.0.1:8000/"

To check complete implementation of Class based FormView, visit FormView – Class Based Views Django
Similar Reads
Django Tutorial | Learn Django Framework
Django is a Python framework that simplifies web development by handling complex tasks for you. It follows the "Don't Repeat Yourself" (DRY) principle, promoting reusable components and making development faster. With built-in features like user authentication, database connections, and CRUD operati
10 min read
Django Basics
Django Basics
Django is a Python-based web framework which allows us to quickly develop robust web application without much third party installations. It comes with many built-in featuresâlike user authentication, an admin panel and form handlingâthat help you build complex sites without worrying about common web
3 min read
Django Installation and Setup
Installing and setting up Django is a straightforward process. Below are the step-by-step instructions to install Django and set up a new Django project on your system.Prerequisites: Before installing Django, make sure you have Python installed on your system. How to Install Django?To Install Django
2 min read
When to Use Django? Comparison with other Development Stacks
Prerequisite - Django Introduction and Installation Django is a high-level Python web framework which allow us to quickly create web applications without all of the installation or dependency problems that we normally face with other frameworks. One should be using Django for web development in the
2 min read
Django Project MVT Structure
Django follows the MVT (Model-View-Template) architectural pattern, which is a variation of the traditional MVC (Model-View-Controller) design pattern used in web development. This pattern separates the application into three main components:1. ModelModel acts as the data layer of your application.
2 min read
How to Create a Basic Project using MVT in Django ?
Prerequisite - Django Project MVT Structure Assuming you have gone through the previous article. This article focuses on creating a basic project to render a template using MVT architecture. We will use MVT (Models, Views, Templates) to render data to a local server. Create a basic Project: To in
2 min read
How to Create an App in Django ?
In Django, an app is a web application that performs a specific functionality, such as blog posts, user authentication or comments. A single Django project can consist of multiple apps, each designed to handle a particular task. Each app is a modular and reusable component that includes everything n
3 min read
Django settings file - step by step Explanation
Once we create the Django project, it comes with a predefined Directory structure having the following files with each file having its own uses. Let's take an example // Create a Django Project "mysite" django-admin startproject mysite cd /pathTo/mysite // Create a Django app "polls" inside project
3 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, a powerful Python web framework, has become one of the most popular choices for web development due to its simplicity, scalability and versatility. One of the key features of Django is its ability to handle views and these views can be implemented using either Class-Based Views (CBVs) or Fun
6 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 Forms
Django Forms
Django Forms are used to gather input from users, validate that input, and process it, often saving the data to the database. For example, when registering a user, a form collects information like name, email, and password.Django automatically maps form fields to corresponding HTML input elements. I
5 min read
How to Create a form using Django Forms
This article explains how to create a basic form using various form fields and attributes. Creating a form in Django is very similar to creating a model, you define the fields you want and specify their types. For example, a registration form might need fields like First Name (CharField), Roll Numbe
2 min read
Django Form | Data Types and Fields
When collecting user input in Django, forms play a crucial role in validating and processing the data before saving it to the database. Django provides a rich set of built-in form field types that correspond to different kinds of input, making it easy to build complex forms quickly.Each form field t
4 min read
Django Form | Build in Fields Argument
We utilize Django Forms to collect user data to put in a database. For various purposes, Django provides a range of model field forms with various field patterns. The most important characteristic of Django forms is their ability to handle the foundations of form construction in only a few lines of
3 min read
Python | Form validation using django
Prerequisites: Django Installation | Introduction to DjangoDjango works on an MVT pattern. So there is a need to create data models (or tables). For every table, a model class is created. Suppose there is a form that takes Username, gender, and text as input from the user, the task is to validate th
5 min read
Render Django Form Fields Manually
Django form fields have several built-in methods to ease the work of the developer but sometimes one needs to implement things manually for customizing User Interface(UI). We have already covered on How to create and use a form in Django?. A form comes with 3 in-built methods that can be used to ren
5 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
User Groups with Custom Permissions in Django - Python
Our task is to design the backend efficiently following the DRY (Don't Repeat Yourself) principle, by grouping users and assigning permissions accordingly. Users inherit the permissions of their groups.Let's consider a trip booking service, how they work with different plans and packages. There is a
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
Extending and customizing django-allauth in Python
Django-allauth is a powerful Django package that simplifies user authentication, registration, account management, and integration with social platforms like Google, Facebook, etc. It builds on Djangoâs built-in authentication system, providing a full suite of ready-to-use views and forms.Prerequisi
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