Table of contents
1.
Introduction
2.
Class-Based Generic Views
3.
Django CRUD (Create, Read, Update, Delete) Using Class-Based Generic Views
3.1.
Class-Based Generic Views
3.1.1.
Function-based view
3.1.2.
Class-based view
4.
CRUD Ninja App
5.
Output
6.
Frequently Asked Questions
6.1.
What are Mixins in Django?
6.2.
What are the advantages of class-based views over function-based views?
6.3.
What are some disadvantages of Class-based Generic views?
6.4.
State some differences between Class-based views and Function-based views?
6.5.
What are the advantages of using Class-Based Generic Views over function-based views in Django?
7.
Conclusion
Last Updated: Mar 27, 2024
Medium

Class-Based Generic Views Django

Author Tanay Kumar Deo
2 upvotes
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Django is one of Python's most popular, trusted, and reliable web development frameworks. With Django, we can quickly create web applications without worrying about installation or dependency problems that we usually find with other frameworks.

Refer to Getting started with Django to learn the basics of Django in detail.

Introduction

In this article, we will learn the Class-Based Generic views in Django. They are the advanced set of Built-in views that can be used to implement the CRUD operations such as retrieve, create, update, and delete. We can easily handle GET, POST requests for a view using Class-Based Generic Views.

Class-Based Generic Views

We can use Class-based Generic views instead of function-based views. The operations are handled using Python objects. Class-based Generic views provide some excellent features over function-based views. They can efficiently perform CRUD operations.
 

  • It follows Django's DRY ( Don't repeat yourself ) convention.
     
  • Using Mixin, we can extend class-based generic views and add more functionalities according to our requirements.
     
  • It allows using the class's inheritance features, which can be helpful in various use cases.

Django CRUD (Create, Read, Update, Delete) Using Class-Based Generic Views

This section will learn how to create and use CRUD views using examples. For the examples in this article, we will consider a project with an app named employe.

CRUD

Class-Based Generic Views

Class-based generic views allow us to handle different HTTP requests using separate class instance methods. This is in contrast to function-based views which handle different HTTP requests by using conditional branching within a single view function. Below is an example of both code to handle HTTP GET requests.

Function-based view

#Importing necessary modules from Django
from django.http import HttpResponse
from django.views import View

#Defining a function-based view called CodingNinjaFunctionalView
def CodingNinjaFunctionalView(request):
# Conditional Branching to check if the request method is 'GET'
if request.method == 'GET':
# View logic will go here
return HttpResponse('result')

Class-based view

#Importing necessary modules from Django
from django.http import HttpResponse
from django.views import View

#Defining a class-based view called CodingNinjaClassView
class CodingNinjaClassView(View):
# Defining the get method that handles GET requests
def get(self, request):
# View logic will go here
return HttpResponse('result')

CRUD Ninja App

Now we are creating a crud project to store data of some ninjas registering on our website.

Step 1: Create a project by typing the below code.

django-admin startproject crud 


The above command starts a new Django project with the name "crud." This will create a new folder called "crud" that includes some required files and directories to start a new Django project.

Step 2: Now we move into the crud folder by typing the below code.

cd crud


Step 3: Now we run the server to check if the Django python is setup or not properly.

python manage.py runserver
python manage.py runserver

 You can now access your Django project in your web browser at http://127.0.0.1:8000/.

Step 4: Now we create a new Django app named "employee" within your Django project. 

python manage.py startapp employee

startapp employee

 

Step 5: Now, we create models inside the employee.

from django.db import models

# Define a Django model named "Ninja"
class Ninja(models.Model):

    # Define the fields of the "Ninja" model
    eid = models.CharField(max_length=20)  # Character field for employee ID
    ename = models.CharField(max_length=100)  # Character field for employee name
    eemail = models.EmailField()  # Email field for employee email address
    econtact = models.CharField(max_length=15)  # Character field for employee contact information

    # Define a string representation for the "Ninja" model
    def __str__(self):
        return "%s " %(self.ename)

    # Define the meta properties of the "Ninja" model
    class Meta:
        db_table = "employee"  # Specify the database table name for the "Ninja" model as "employee"

 

Step 6: Now we create form.py. The below code state the Django form with the name NinjaDetails. It is based on the Ninja model. Where forms.ModelForm class is used as a base class for the NinjaDetails form, which provides a  way to create a form based on a model.

from django import forms  
from employee.models import Ninja
from django.forms import fields

class NinjaDetails(forms.ModelForm):  
    class Meta:  
        model = Ninja  
        fields = "__all__"  


Step 7: Now we set up views.py. The below code you will see defines several views that interact with the Ninja model and the NinjaDetails form to implement a basic CRUD (Create, Read, Update, Delete) application.

from django.shortcuts import render
from django.shortcuts import render, redirect  
from employee.forms import NinjaDetails  
from employee.models import Ninja  
 
def emp(request):  
    if request.method == "POST":  
        form = NinjaDetails(request.POST)  
        if form.is_valid():  
            try:  
                form.save()  
                return redirect('/show')  
            except:  
                pass  
    else:  
        form = NinjaDetails()  
    return render(request,'index.html',{'form':form})  
def show(request):  
    employees = Ninja.objects.all()  
    return render(request,"show.html",{'employees':employees})  
def edit(request, id):  
    employee = Ninja.objects.get(id=id)  
    return render(request,'edit.html', {'employee':employee})  
def update(request, id):  
    employee = Ninja.objects.get(id=id)  
    form = NinjaDetails(request.POST, instance = employee)  
    if form.is_valid():  
        form.save()  
        return redirect("/show")  
    return render(request, 'edit.html', {'employee': employee})  
def destroy(request, id):  
    employee = Ninja.objects.get(id=id)  
    employee.delete()  
    return redirect("/show")

 

Step 8: Now we set URL to route the links where we want to. It is very simple. The below url.py file is from the crud folder where we include the employee.url.

from django.contrib import admin
from django.urls import path
from django.urls.conf import include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('employee.urls'))
]

 

Below is the url.py file from the employee folder where we have routed everything.

from django.contrib import admin  
from django.urls import path  
from employee import views  

urlpatterns = [  
    path('admin/', admin.site.urls),  
    path('emp', views.emp),  
    path('show',views.show),  
    path('edit/<int:id>', views.edit),  
    path('update/<int:id>', views.update),  
    path('delete/<int:id>', views.destroy),  
]  


Step 9: Now, create a templates folder for the frontend part. I will not be explaining the fronted part in deep because it will kill your time as well if you are learning crud you suppose to be aware of the simple frontend thing.

Structure Inside the templates folder:

templates file structure

index.html code:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    {% load static %}
    <link rel="stylesheet" href="{% static 'css/style.css' %}">
</head>

<body>
    <form method="POST" action="/emp">
        {% csrf_token %}
        <div>
            <br>
            <p>
                <h3>Enter Details</h3>
            </p>
            <div>
                <p>Ninja Id:</p>{{ form.eid }}
            </div>
            <div>
                <p>Ninja Name::</p>{{ form.ename }}
            </div>
            <div>
                <p>Ninja Email:</p>{{ form.eemail }}
            </div>
            <div>
                <p>Ninja contact:</p>{{ form.econtact }}
            </div>
            <div>
                <br>
                <button type="submit">Submit</button>
            </div>
        </div>
    </form>
</body>

</html>


Show.html code:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ninja Record</title>
    {% load static %}
    <link rel="stylesheet" href="{% static 'css/style.css' %}">
</head>

<body>
    <table>
        <thead>
            <tr>
                <th>Ninja ID</th>
                <th>Ninja Name</th>
                <th>Ninja Email</th>
                <th>Ninja Contact</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            {% for employee in ninjas %}
            <tr>
                <td>{{ employee.eid }}</td>
                <td>{{employee.ename}}</td>
                <td>{{employee.eemail}}</td>
                <td>{{employee.econtact}}</td>
                <td>
                    <a href="/edit/{{ employee.id }}">Edit</a>
                    <a href="/delete/{{employee.id}}">Delete</a>
                </td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
    <br>
    <br>
    <button><a style="color:white;" href="/emp">Add New Record</a></button>
</body>

</html>

 

edit.html code

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    {% load static %}
    <link rel="stylesheet" href="{% static 'css/style.css' %}">
</head>

<body>
    <form method="POST" action="/update/{{employee.id}}">
        {% csrf_token %}
        <div>
            <br>
            <p>
                <h3>Update Details</h3>
            </p>
        </div>
        <div>
            <p>Ninja Id:</p>
            <div>
                <input type="text" name="eid" value="{{employee.eid}}" />
            </div>
        </div>
        <div>
            <p>Ninja Name:</p>
            <div>
                <input type="text" name="ename" value="{{employee.ename}}" />
            </div>
        </div>
        <div>
            <p>Ninja Email :</p>
            <div>
                <input type="email" name="eemail" value="{{employee.eemail}}" />
            </div>
        </div>
        <div>
            <p>Ninja Contact:</p>
            <div>
                <input type="text" name="econtact" value="{{employee.econtact}}" />
            </div>
        </div>
        <div>
            <br>
            <button type="submit">Update</button>
        </div>
    </form>
</body>
</html>


Step 10: Now make migration by typing below code.

Python manage.py makemigrations
Python manage.py migrate

Python manage.py makemigrations is a command used in the Django web framework to create new database migration files based on changes to the models (database tables) defined in the code.

Python manage.py migrate is a command used in the Django web framework to apply those migration files to the database, updating the schema and data accordingly.

Step 11: Create a Static folder for style.css, below is the file structure and code.

 

static file structure

style.css

body {
    background: #ff8c00;
    height: 100%;
    margin: 100px 0;
    padding-left: 300px;
}

table,
th,
td {
    border: 5px solid rgb(1, 27, 34);
    height: 50px;
    width: 150px;
    background-color: cadetblue;
}



th {
    background-color: #ffffff;
    color: rgb(0, 0, 0);
    height: 50px;
    width: 150px;
    background-color: bisque;
}

button {
    border-radius: 12px;
    color: rgb(123, 7, 225);
    background-color: #000000;
    cursor: pointer;
    height: 50px;
    width: 200px;
}


Hurree, Now run the python manage.py runserver to open the website.

As we have set the URL to http://127.0.0.1:8000/show open this link only.
 

NOTE: Make sure you add your employee app in the setting.py file in the section of INSTALLED_APP by typing 'employee'

Output

Output
Output

Frequently Asked Questions

What are Mixins in Django?

Mixins are classes in Django that provide additional functionality to Class-Based Generic Views. They allow us to add new functionalities to existing views without repeating the code and provide a way of code reusability.

What are the advantages of class-based views over function-based views?

Class-Based views have a lot of advantages over function-based views. The most significant advantage of the class-based view is inheritance. We can also extend class-based views and add more functionalities with Mixins. It has Built-in class-based generic views.

What are some disadvantages of Class-based Generic views?

There are a few disadvantages of class-based generic views. It becomes harder to read the codes in the parent class as not all the codes are available in a single location.Also use of view decorators require extra import or method override.

State some differences between Class-based views and Function-based views?

Function-based views are easy and simple to implement, have explicit code flow, and have straightforward usage of decorators. 
With Class-based views, we can easily extend and reuse codes using inheritance and built-in class-based generic views.

What are the advantages of using Class-Based Generic Views over function-based views in Django?

Class-Based Generic Views provide several advantages over function-based views, such as DRY convention, inheritance, mixins, and efficient handling of CRUD operations using Python objects.

Conclusion

In this article, we have discussed the class-based generic views and how they are different from function-based views. We also implemented the CRUD operations using the in-built views.

If you want to rock in your tech interviews, you have to practice various questions, and let me share with you the Coding Ninjas Studio  platform where you can find questions asked in all big-tech giants.

Refer to our Guided Paths on Coding Ninjas Studio to learn more about DSA, JavaScript, System Design, DBMS, Java, etc. Enrol in our courses and refer to the mock test and problems available. Take a look at the interview experiences and interview bundle for placement preparations.

We hope you found this blog helpful. Like the blog? Then feel free to upvote and share it.

Live masterclass