The Wayback Machine - https://web.archive.org/web/20240910172728/https://www.geeksforgeeks.org/class-based-generic-views-django-create-retrieve-update-delete/
Open In App

Class Based Generic Views Django (Create, Retrieve, Update, Delete)

Last Updated : 21 Sep, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Django is a Python-based web framework that allows you to quickly create web applications. It has built-in admin interface which makes easy to work with it. It is often called Batteries included framework because it provides built-in facilities for every functionality. Class Based Generic Views are advanced set of Built-in views which are used for implementation of selective view strategies such as Create, Retrieve, Update, Delete. Class based views simplify the use by separating GET, POST requests for a view. They do not replace function-based views, but have certain differences and advantages when compared to function-based views:

  • Organization of code related to specific HTTP methods (GET, POST, etc.) can be addressed by separate methods instead of conditional branching.
  • Object oriented techniques such as mixins (multiple inheritance) can be used to factor code into reusable components.

This article revolves around complete implementation of Class Based Views in Django (Create, Retrieve, Update, Delete). Let’s discuss what actually CRUD means,

Untitled-Diagram-316

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 CRUD (Create, Retrieve, Update, Delete) Class Based Views

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. 

After you have a project and an app, let’s create a model of which we will be creating instances through our view. In geeks/models.py,  

Python3




# import the standard Django Model
# from built-in library
from django.db import models
  
# declare a new model with a name "GeeksModel"
class GeeksModel(models.Model):
 
    # fields of the model
    title = models.CharField(max_length = 200)
    description = models.TextField()
 
    # renames the instances of the model
    # with their title name
    def __str__(self):
        return self.title


After creating this model, we need to run two commands in order to create Database for the same. 

Python manage.py makemigrations
Python manage.py migrate

Now we will create a Django ModelForm for this model. Refer this article for more on modelform – Django ModelForm – Create form from Models. create a file forms.py in geeks folder,  

Python3




from django import forms
from .models import GeeksModel
 
 
# creating a form
class GeeksForm(forms.ModelForm):
 
    # create meta class
    class Meta:
        # specify model to be used
        model = GeeksModel
 
        # specify fields to be used
        fields = [
            "title",
            "description",
        ]


Using Class Based Views

At its core, a class-based view allows you to respond to different HTTP request methods with different class instance methods, instead of with conditionally branching code inside a single view function.

So where the code to handle HTTP GET in a view function would look something like: 

Python3




from django.http import HttpResponse
 
def my_view(request):
    if request.method == 'GET':
        # <view logic>
        return HttpResponse('result')


In a class-based view, this would become:

Python3




from django.http import HttpResponse
from django.views import View
 
class MyView(View):
    def get(self, request):
        # <view logic>
        return HttpResponse('result')


Similarly in urls.py, one needs to use as_view() method to differentiate a class based view from function based view. 

Python3




# urls.py
from django.urls import path
from myapp.views import MyView
 
urlpatterns = [
 
    path('about/', MyView.as_view()),
 
]


CreateView

Create View refers to a view (logic) to create an instance of a table in the database. We have already discussed basics of Create View in Create View – Function based Views Django. Class Based Views automatically setup everything from A to Z. One just needs to specify which model to create Create View for and the fields. Then Class based CreateView will automatically try to find a template in app_name/modelname_form.html. In our case it is geeks/templates/geeks/geeksmodel_form.html. Let’s create our class based view. In geeks/views.py, 

Python3




from django.views.generic.edit import CreateView
from .models import GeeksModel
 
class GeeksCreate(CreateView):
 
    # specify the model for create view
    model = GeeksModel
 
    # specify the fields to be displayed
 
    fields = ['title', 'description']


Now create a url path to map the view. In geeks/urls.py, 

Python3




from django.urls import path
 
# importing views from views..py
from .views import GeeksCreate
urlpatterns = [
    path('', GeeksCreate.as_view() ),
]


Create a template in templates/geeks/geeksmodel_form.html, 

HTML




<form method="POST" enctype="multipart/form-data">
 
    <!-- Security token -->
    {% csrf_token %}
 
    <!-- Using the formset -->
    {{ form.as_p }}
     
    <input type="submit" value="Submit">
</form>


Let’s check what is there on http://localhost:8000/ 

django-create-view-function-based

To check complete implementation of Class based CreateView, visit Createview – Class Based Views Django. 

Retrieve Views

ListView

List View refers to a view (logic) to display multiple instances of a table in the database. We have already discussed basics of List View in List View – Function based Views Django. Class Based Views automatically setup everything from A to Z. One just needs to specify which model to create ListView for, then Class based ListView will automatically try to find a template in app_name/modelname_list.html. In our case it is geeks/templates/geeks/geeksmodel_list.html. Let’s create our class based view. In geeks/views.py, 

Python3




from django.views.generic.list import ListView
from .models import GeeksModel
 
class GeeksList(ListView):
 
    # specify the model for list view
    model = GeeksModel


Now create a url path to map the view. In geeks/urls.py, 

Python3




from django.urls import path
 
# importing views from views..py
from .views import GeeksList
urlpatterns = [
    path('', GeeksList.as_view()),
]


Create a template in templates/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>


Let’s check what is there on http://localhost:8000/ 

django-listview-class-based-views

To check complete implementation of Class based ListView, visit ListView – Class Based Views Django

DetailView

Detail View refers to a view (logic) to display one instances of a table in the database. We have already discussed basics of Detail View in Detail View – Function based Views Django. Class Based Views automatically setup everything from A to Z. One just needs to specify which model to create DetailView for, then Class based DetailView will automatically try to find a template in app_name/modelname_detail.html. In our case it is geeks/templates/geeks/geeksmodel_detail.html. Let’s create our class based view. In geeks/views.py, 

Python3




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, 

Python3




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/ 

django-detailview-class-based

To check complete implementation of Class based DetailView, visit DetailView – Class Based Views Django 

UpdateView

UpdateView refers to a view (logic) to update a particular instance of a table from the database with some extra details. It is used to update entries in the database for example, updating an article at geeksforgeeks. We have already discussed basics of Update View in Update View – Function based Views Django. Class Based Views automatically setup everything from A to Z. One just needs to specify which model to create UpdateView for, then Class based UpdateView will automatically try to find a template in app_name/modelname_form.html. In our case it is geeks/templates/geeks/geeksmodel_form.html. Let’s create our class based view. In geeks/views.py, 

Python3




# import generic UpdateView
from django.views.generic.edit import UpdateView
 
# Relative import of GeeksModel
from .models import GeeksModel
 
class GeeksUpdateView(UpdateView):
    # specify the model you want to use
    model = GeeksModel
 
    # specify the fields
    fields = [
        "title",
        "description"
    ]
 
    # can specify success url
    # url to redirect after successfully
    # updating details
    success_url ="/"


Now create a url path to map the view. In geeks/urls.py, 

Python3




from django.urls import path
 
# importing views from views..py
from .views import GeeksUpdateView
urlpatterns = [
    # <pk> is identification for id field,
    # <slug> can also be used
    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/ 

django-updateview-class-based-view

To check complete implementation of Class based UpdateView, visit UpdateView – Class Based Views Django. 

DeleteView

Delete View refers to a view (logic) to delete a particular instance of a table from the database. It is used to delete entries in the database for example, deleting an article at geeksforgeeks. We have already discussed basics of Delete View in Delete View – Function based Views Django. Class Based Views automatically setup everything from A to Z. One just needs to specify which model to create DeleteView for, then Class based DeleteViewde will automatically try to find a template in app_name/modelname_confirm_delete.html. In our case it is geeks/templates/geeks/geeksmodel_confirm_delete.html. Let’s create our class based view. In geeks/views.py, 

Python3




# import generic UpdateView
from django.views.generic.edit import DeleteView
 
# Relative import of GeeksModel
from .models import GeeksModel
 
class GeeksDeleteView(DeleteView):
    # specify the model you want to use
    model = GeeksModel
     
    # can specify success url
    # url to redirect after successfully
    # deleting object
    success_url ="/"


Now create a url path to map the view. In geeks/urls.py, 

Python3




from django.urls import path
 
# importing views from views..py
from .views import GeeksDeleteView
urlpatterns = [
    # <pk> is identification for id field,
    # slug can also be used
    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 

django-deleteview-class-based-views

To check complete implementation of Class based DeleteView, visit DeleteView – Class Based Views Django

FormView

FormView refers to a view (logic) to display and verify a Django Form. For example a form to register users at geeksforgeeks. Class Based Views automatically setup everything from A to Z. One just needs to specify which form to create FormView for and template_name, then Class based FormView will automatically render that form. Let’s create our class based view. In geeks/views.py,  

Python3




# import generic FormView
from django.views.generic.edit import FormView
 
# Relative import of GeeksForm
from .forms import GeeksForm
 
class GeeksFormView(FormView):
    # specify the Form you want to use
    form_class = GeeksForm
     
    # specify name of template
    template_name = "geeks / geeksmodel_form.html"
 
    # can specify success url
    # url to redirect after successfully
    # updating details
    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, 

Python3




from django.urls import path
 
# importing views from views..py
from .views import GeeksFormView
urlpatterns = [
    path('', GeeksFormView.as_view()),
]


Now visit http://127.0.0.1:8000/, 

django-create-view-function-based

To check complete implementation of Class based FormView, visit FormView – Class Based Views Django
 



Previous Article
Next Article

Similar Reads

Django CRUD (Create, Retrieve, Update, Delete) 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, Update, Delete) operations. CRUD can be best explain
7 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 of the flow of the project. How things run in the
7 min read
Update View - Function based Views Django
Update View refers to a view (logic) to update a particular instance of a table from the database with some extra details. It is used to update entries in the database for example, updating an article at geeksforgeeks. So Update view must display the old data in the form and let user update the data from there only. Django provides extra-ordinary s
4 min read
Delete View - Function based Views Django
Delete View refers to a view (logic) to delete a particular instance of a table from the database. It is used to delete entries in the database for example, deleting an article at geeksforgeeks. So Delete view must show a confirmation message to the user and should delete the instance automatically. Django provides extra-ordinary support for Delete
3 min read
Create View - Function based Views Django
Create View refers to a view (logic) to create an instance of a table in the database. It is just like taking an input from a user and storing it in a specified table. Django provides extra-ordinary support for Create Views but let's check how it is done manually through a function-based view. This article revolves around Create View which involves
3 min read
Createview - Class Based Views Django
Create View refers to a view (logic) to create an instance of a table in the database. We have already discussed basics of Create View in Create View – Function based Views Django. Class-based views provide an alternative way to implement views as Python objects instead of functions. They do not replace function-based views, but have certain differ
3 min read
ListView - Class Based Views Django
List View refers to a view (logic) to display multiple instances of a table in the database. We have already discussed the basics of List View in List View – Function based Views Django. Class-based views provide an alternative way to implement views as Python objects instead of functions. They do not replace function-based views, but have certain
4 min read
UpdateView - Class Based Views Django
UpdateView refers to a view (logic) to update a particular instance of a table from the database with some extra details. It is used to update entries in the database, for example, updating an article at geeksforgeeks. We have already discussed basics of Update View in Update View – Function based Views Django. Class-based views provide an alternat
3 min read
DetailView - Class Based Views Django
Detail View refers to a view (logic) to display one instances of a table in the database. We have already discussed basics of Detail View in Detail View – Function based Views Django. Class-based views provide an alternative way to implement views as Python objects instead of functions. They do not replace function-based views, but have certain dif
3 min read
DeleteView - Class Based Views Django
Delete View refers to a view (logic) to delete a particular instance of a table from the database. It is used to delete entries in the database for example, deleting an article at geeksforgeeks. We have already discussed basics of Delete View in Delete View – Function based Views Django. Class-based views provide an alternative way to implement vie
3 min read
FormView - Class Based Views Django
FormView refers to a view (logic) to display and verify a Django Form. For example, a form to register users at Geeksforgeeks. Class-based views provide an alternative way to implement views as Python objects instead of functions. They do not replace function-based views, but have certain differences and advantages when compared to function-based v
3 min read
Class based views - Django Rest Framework
Class-based views help in composing reusable bits of behavior. Django REST Framework provides several pre-built views that allow us to reuse common functionality and keep our code DRY. In this section, we will dig deep into the different class-based views in Django REST Framework. This article assumes you are already familiar with Django and Django
12 min read
TemplateView - Class Based Generic View Django
Django provides several class based generic views to accomplish common tasks. The simplest among them is TemplateView. It Renders a given template, with the context containing parameters captured in the URL. TemplateView should be used when you want to present some information on an HTML page. TemplateView shouldn’t be used when your page has forms
2 min read
Use Pagination with Django Class-Based Generic ListView
Pagination is a crucial feature for any web application that displays a large set of data. It helps manage the data load by breaking it into smaller, more manageable chunks, enhancing user experience and performance. Django ships with predefined generic views that we can use to build our application with minimal code changes. The Generic ListView i
3 min read
Detail View - Function based Views Django
Detail View refers to a view (logic) to display a particular instance of a table from the database with all the necessary details. It is used to display multiple types of data on a single page or view, for example, profile of a user. Django provides extra-ordinary support for Detail Views but let's check how it is done manually through a function-b
3 min read
List View - Function based Views Django
List View refers to a view (logic) to list all or particular instances of a table from the database in a particular order. It is used to display multiple types of data on a single page or view, for example, products on an eCommerce page. Django provides extra-ordinary support for List Views but let's check how it is done manually through a function
3 min read
Function based Views - Django Rest Framework
Django REST Framework allows us to work with regular Django views. It facilitates processing the HTTP requests and providing appropriate HTTP responses. In this section, you will understand how to implement Django views for the Restful Web service. We also make use of the @api_view decorator. Before working on Django REST Framework serializers, you
13 min read
Retrieve PDF File in Django From Firebase
Firebase is a product of Google which helps developers to build, manage, and grow their apps easily. It helps developers to build their apps faster and in a more secure way. No programming is required on the firebase side which makes it easy to use its features more efficiently. It provides cloud storage and uses NoSQL for the storage of data. Djan
5 min read
Built-in Error Views in Django
Whenever one tries to visit a link that doesn't exist on a website, it gives a 404 Error, that this page is not found. Similarly, there are more error codes such as 500, 403, etc. Django has some default functions to for handle HTTP errors. Let's explore them one-by-one. Built-in Error Views in Django - 404 view (page not found) - Normally this vie
3 min read
Render a HTML Template as Response - Django Views
A view function, or view for short, is simply a Python function that takes a Web request and returns a Web response. This article revolves around how to render an HTML page from Django using views. Django has always been known for its app structure and ability to manage applications easily. Let's dive in to see how to render a template file through
3 min read
Raw SQL queries in Django views
Let's create a simple Django project that demonstrates the use of raw SQL queries in a view. In this example, we'll create a project to manage a list of books stored in a database. We'll create a view that retrieves books from the database using a raw SQL query and displays them on a webpage. Setting up the projectWe assume that Django is already i
4 min read
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 image, or anything that a web browser can display.  D
6 min read
How to Pass Additional Context into a Class Based View (Django)?
Passing context into your templates from class-based views is easy once you know what to look out for. There are two ways to do it - one involves get_context_data, the other is by modifying the extra_context variable. Let see how to use both the methods one by one. Explanation: Illustration of How to use get_context_data method and extra_context va
2 min read
How to retrieve source code from Python objects?
We are given a object and our task is to retrieve its source code, for this we have inspect module, dill module and dis module built-in standard libraries in Python programming. They provide several useful functions to track information about live objects such as modules, classes, methods, functions, tracebacks, frame objects, and code objects. get
2 min read
How to Retrieve an Entire Row or Column of an Array in Python?
Arrays are a set of similar elements grouped together to form a single entity, that is, it is basically a collection of integers, floating-point numbers, characters etc. The indexing of the rows and columns start from 0. Uni-Dimensional Arrays Uni-dimensional arrays form a vector of similar data-type belonging elements. It contains a single row of
4 min read
Retrieve Image and File stored as a BLOB from MySQL Table using Python
Prerequisites: MySQL server should be installed In this post, we will be talking about how we can store files like images, text files, and other file formats into a MySQL table from a python script. Sometimes, just like other information, we need to store images and files into our database and provide it the security equivalent to other data. In My
3 min read
Retrieve children of the html tag using BeautifulSoup
Prerequisites: Beautifulsoup Beautifulsoup is a Python module that is used for web scraping. This article discusses how children tags of given HTML tags can be scraped and displayed. Sample Website:https://www.geeksforgeeks.org/caching-page-tables/ For First Child: Approach Import modulePass the URLRequest pageDisplay the first child using findChil
3 min read
PySpark Collect() – Retrieve data from DataFrame
Collect() is the function, operation for RDD or Dataframe that is used to retrieve the data from the Dataframe. It is used useful in retrieving all the elements of the row from each partition in an RDD and brings that over the driver node/program. So, in this article, we are going to learn how to retrieve the data from the Dataframe using collect()
6 min read
Retrieve Text From Textarea in Flask
In this article, we will see how we can retrieve the elements inside the textarea tag using Python. Textarea is one of the popular tags we used in HTML. To retrieve text from a textarea in Flask, you can use the request.form.get() method. This method allows you to retrieve the value of a specific form field, such as a textarea, from the request dat
2 min read
Retrieve elements from Python Set
In this article, we will discuss the different examples of how to retrieve an element from a Python set in Python. Examples to Retrieve elements from Python SetRetrieve all elements from a set without a duplicate value By iterating the elements in a set using for loop we can get all the unique set elements. C/C++ Code # create a set with integer el
3 min read
Practice Tags :