CRUD operations in Django

CRUD in Django

Today, we will learn how to perform CRUD operations in Django Python. We will perform CRUD operations using a form and without a form. We will use the absolute beginner-friendly approach in this article so that even a 1-day beginner of Django can understand how to perform CRUD operations in Django Python. Let’s start.

CRUD stands for:
C – Create
R – Read
U – Update
D – Delete

CRUD operations in Django using Form

Creating a new Django project

First, we will create a new project using the command in cmd:

django-admin startproject projectname

Then we will step into the project file using the command:

cd projectname

Then we will make an application in the project using the command:

django-admin startapp appname

Now we will open the project folder in coding software like sublime, vs code, etc.

Project Folder Structure

The project folder structure should follow the following hierarchy:

folder structure for CRUD operations in Django using Form

Now we will open the models.py file

A model is a class that represents a table or collection in our Database, and where every attribute of the class is a field of the table or collection.

Now install the app in the settings.py file in this section

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app', 🡨
]

models.py

Here, I need to save information about students.

from django.db import models
 
class Student(models.Model): # the name of class represent table name in database
    name = models.CharField(max_length = 255)
    email = models.EmailField()
    roll_number = models.IntegerField()
    section = models.CharField(max_length = 3)

CharField: this represents the string datatype in the database
EmailField: this field takes care of email essential elements in the field like @ and .com
IntegerField: this field represents a numeric datatype in the database.

Note: It is important to define max_length as a parameter whenever you are using CharFiled.

In the terminal, run the command

python manage.py makemigrations
python manage.py migrate

This command will create and commit the tables in the database.

Now we will make a new file in the app with the name forms.py

forms.py

Now, we need to connect our form file with Django’s inbuilt form file so we need to import the form as follows:

from django.form import form

Then we also have to connect our database with our form file so this code is to import a particular table/class from model.py

from .models import Student

And this command is to import all the tables/classes present in models.py

from .models import *

Now make a class and name the class as follow:

from django import forms
from .models import Student		
 
class StudentForm(forms.ModelForm):
    class Meta:
        model = Student
        fields = "__all__"

Here, StudentForm is the model form class name, model = Student represents in which table you need to store the information you this form, and fields = “__all__” represents the model field you need to show in frontend side.

Create in CRUD operations in Django using Form

Create usually refers to the insertion of new values that we insert into a table in a database.

Create a folder in the app and name it as templates, then make a file in the side template folder and name that file index.html

index.html file

views.py

First import forms and models in views.py 

from .forms import *
from .models import *

Now, make a function and define code to create the user interface and save the data we get from the user in the database

def create(request):
    if request.method == 'POST':
        fm = StudentForm(request.POST)
        if fm.is_valid():
            fm.save()
    else:
        fm = StudentForm()
    return render(request,'index.html',{'fm':fm})

fm is a variable representing an instance of StudentForm class which we will use to show fields on the user side 

POST method is used to get data from HTML and then save it using fm.save() and fm.is_valid() is used to check data from the HTML page is in the correct format or not.

index.html

<!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>Student Form</title>
</head>
<body>
    <form method="POST">
        {% csrf_token %}
        {{fm}}
        <button type="submit">submit</button>
    </form>
</body>
</html>

url.py

from django.contrib import admin
from django.urls import path
from app import views
 
urlpatterns = [
    path('admin/', admin.site.urls),
    path('',views.create,name='create')
]

Output for Create operation:

output for create operation in CRUD operations in Django using Form

Read in CRUD operations in Django using Form

Read means to show the data from the database

views.py

def read(request):
    data = Student.objects.all()
    return render(request,'read.html',{'data':data})

create a new file in the templates folder and name the file read.html

read.html

<!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>Student Form</title>
</head>
<body>
    <table border="1">
        <th>
            <td>Student Name</td>
            <td>Email</td>
            <td>Roll Numder</td>
            <td>Section</td>
        </th>
        
        {% for i in data %}
        <tr><td></td>
            <td>{{i.name}}</td>
            <td>{{i.email}}</td>
            <td>{{i.roll_number}}</td>
            <td>{{i.section}}</td>
        </tr>
        {% endfor %}
            
        
    </table>
</body>
</html>

We need to use jinja tags to show data. here we have used for loop to show multiple data.

output for read operation in CRUD operations in Django using Form

We can also define create and read operations in one single page and in one function also.

def create(request):
    if request.method == 'POST':
        fm = StudentForm(request.POST)
        if fm.is_valid():
            fm.save()
            return redirect('create')
    else:
        fm = StudentForm()
        data = Student.objects.all()
    return render(request,'index.html',{'fm':fm,'data':data})

index.html

<!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>Student Form</title>
</head>
<body>
    <form method="POST">
        {% csrf_token %}
        {{fm}}
        <button type="submit">submit</button>
    </form>
    <br>
    <table border="1">
        <th>
            <td>Student Name</td>
            <td>Email</td>
            <td>Roll Numder</td>
            <td>Section</td>
        </th>
        
        {% for i in data %}
        <tr><td></td>
            <td>{{i.name}}</td>
            <td>{{i.email}}</td>
            <td>{{i.roll_number}}</td>
            <td>{{i.section}}</td>
        </tr>
        {% endfor %}  
    </table>
</body>
</html>

Output for Read operation:

final output for read operation in CRUD

Update in CRUD operations in Django using Form

In update operation, we need to update or change data that is already present in our database.

So, to select particular data we need to get the id of that data

In index.html we make two buttons one for delete and the other for update

<!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>Student Form</title>
</head>
<body>
    <form method="POST">
        {% csrf_token %}
        {{fm}}
        <button type="submit">submit</button>
    </form>
    <br>
    <table border="1">
        <th>
            <td>Student Name</td>
            <td>Email</td>
            <td>Roll Numder</td>
            <td>Section</td>
            <td>Action</td>
        </th>
        
        {% for i in data %}
        <tr><td></td>
            <td>{{i.name}}</td>
            <td>{{i.email}}</td>
            <td>{{i.roll_number}}</td>
            <td>{{i.section}}</td>
            <td><button>Update</button>
            <button>Delete</button></td>
        </tr>
        {% endfor %}  
    </table>
</body>
</html>

views.py

Now create a view function name edit in views.py

def edit(request,id):
    dataget = Student.objects.get(id=id)
    data = Student.objects.all()
    fm = StudentForm(instance=dataget)
    if request.method == 'POST':
        fm = StudentForm(request.POST,instance=dataget)
        if fm.is_valid():
            fm.save()
            return redirect('create')
    return render(request,'index.html',{'fm':fm,'data':data})

index.html

<!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>Student Form</title>
</head>
<body>
    <form method="POST">
        {% csrf_token %}
        {{fm}}
        <button type="submit">submit</button>
    </form>
    <br>
    <table border="1">
        <th>
            <td>Student Name</td>
            <td>Email</td>
            <td>Roll Numder</td>
            <td>Section</td>
            <td>Action</td>
        </th>
        
        {% for i in data %}
        <tr><td></td>
            <td>{{i.name}}</td>
            <td>{{i.email}}</td>
            <td>{{i.roll_number}}</td>
            <td>{{i.section}}</td>
            <td><a href="{% url 'update' i.id %}"><button>Update</button></a>
            <button>Delete</button></td>
        </tr>
        {% endfor %}  
    </table>
</body>
</html>

{% url ‘update’ i.id %} here update is a function path and i.id gives a the id of selected item.

urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',views.create,name='create'),
    path('read/',views.read,name='read'),
    path('update/<int:id>/',views.edit,name='update')
]

Output for Update operation:

Select the item here item id is 2

output 1 for update operation in CRUD operations in Django using Form

Change the section from C to D

output 2 for update operation in CRUD

Delete in CRUD operations in Django using Form

To delete a selected item from the database follow the steps below

def delete(request,id):
    dataget = Student.objects.get(id=id)
    dataget.delete()
    return redirect('create')

To delete here we have to use delete()

Output for Delete operation:

This function fetches the id and then deletes that selected id item from the database

output 1 for delete operation

The item with id 3 is deleted from our list.

output 2 for delete operation

CRUD operations in Django without Form

Creating a new Django project

First, we will create a new project using the command in cmd:

django-admin startproject projectname

Then we will step into the project file using the command:

cd projectname

Then we will make an application in the project using the command:

django-admin startapp appname

Now we will open the project folder in coding software like sublime, vs code, etc.

Project Folder Structure

The project folder structure should follow the following hierarchy

folder structure for CRUD operations in Django without Form

Now we will open the models.py file

A model is a class that represents a table or collection in our Database, and where every attribute of the class is a field of the table or collection.

Now install the app in the settings.py file in this section

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app', 🡨
]

models.py

Here, I need to save information about students. 

from django.db import models
 
class Student(models.Model): # the name of class represent table name in database
    name = models.CharField(max_length = 255)
    email = models.EmailField()
    roll_number = models.IntegerField()
    section = models.CharField(max_length = 3)

CharField: this represents the string datatype in the database
EmailField: this field takes care of email essential elements in the field like @ and .com
IntegerField: this field represents a numeric datatype in the database.

Note: It is important to define max_length as a parameter whenever you are using CharFiled.

In the terminal run, the command

python manage.py makemigrations
python manage.py migrate

This command will create and commit the tables in the database.

Create in CRUD operations in Django without Form

Create a new folder inside the app folder and name it templates

index.html file

Open views.py

views.py

First import models in views.py 

from .models import *

make a function and define code to create the user interface and save the data we get from the user in the database.

request object represents a single request by any user agent. So it can be a request that’s sent from a browser from you when you browse a particular page or from a crawler from a search engine. Read more about the request here.

request.POST is an attribute of this request object, it’s a QueryDict (much similar to a normal Python dict). It contains the HTTP POST parameters that are sent to your view.

def create(request):
    if request.method == 'POST':
        name = request.POST['name']
        email = request.POST['email']
        roll = request.POST['roll']
        section = request.POST['section']
        Student(name=name,
                email=email,
                roll_number = roll,
                section =section).save()
        return redirect('create')
    return render(request,'index.html')

index.html

<!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>Student Form</title>
</head>
<body>
    <form method="POST">
        {% csrf_token %}
        <label >Name:</label>
        <input type="text" name="name" >
        <label >Email:</label>
        <input type="text" name="email" >
        <label >Roll Number:</label>
        <input type="text" name="roll">
        <label >Section:</label>
        <input type="text" name="section">
        <button type="submit">submit</button>
    </form>
</body>
</html>

urls.py

from django.contrib import admin
from django.urls import path
from app import views
 
urlpatterns = [
    path('admin/', admin.site.urls),
    path('',views.create,name='create'),
]

Output for Create operation:

output for create operation in CRUD operations in Django without form

Read in CRUD operations in Django without Form

As we discuss above it means showing the data from the database.

Here method to show data is defined in the same function as the creation

def create(request):
    if request.method == 'POST':
        name = request.POST['name']
        email = request.POST['email']
        roll = request.POST['roll']
        section = request.POST['section']
        Student(name=name,
                email=email,
                roll_number = roll,
                section =section).save()
        return redirect('create')
 
    data = Student.objects.all()🡨-----------
    return render(request,'index.html',{'data':data})

index.html

<!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>Student Form</title>
</head>
<body>
    <form method="POST">
        {% csrf_token %}
        <label >Name:</label>
        <input type="text" name="name" >
        <label >Email:</label>
        <input type="text" name="email">
        <label >Roll Number:</label>
        <input type="text" name="roll" >
        <label >Section:</label>
        <input type="text" name="section" >
        <button type="submit">submit</button>
    </form>
    <br>
    <table border="1">
        <th>
            <td>Student Name</td>
            <td>Email</td>
            <td>Roll Numder</td>
            <td>Section</td>
            <td>Action</td>
        </th>
        
        {% for i in data %}
        <tr><td></td>
            <td>{{i.name}}</td>
            <td>{{i.email}}</td>
            <td>{{i.roll_number}}</td>
            <td>{{i.section}}</td>
            <td><a href="#"><><button>Update</button></a>
            <a href="#"><button>Delete</button></a></td>
        </tr>
        {% endfor %}  
    </table>
</body>
</html>

Output for Read operation:

output for read operation

Update in CRUD operations in Django without Form

views.py

def edit(request,id):
    dataget = Student.objects.get(id = id)
    data = Student.objects.all()
    if request.method == "POST":
        name = request.POST['name']
        email = request.POST['email']
        roll = request.POST['roll']
        section = request.POST['section']
        dataget.name = name
        dataget.email = email
        dataget.roll_number = roll
        dataget.section = section
        dataget.save()
        return redirect('create')
    return render(request,'index.html',{'dataget':dataget,'data':data})

index.html

<!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>Student Form</title>
</head>
<body>
    <form method="POST">
        {% csrf_token %}
        <label >Name:</label>
        <input type="text" name="name" value="{{dataget.name}}">
        <label >Email:</label>
        <input type="text" name="email" value="{{dataget.email}}">
        <label >Roll Number:</label>
        <input type="text" name="roll" value="{{dataget.roll_number}}">
        <label >Section:</label>
        <input type="text" name="section" value="{{dataget.section}}">
        <button type="submit">submit</button>
    </form>
    <br>
    <table border="1">
        <th>
            <td>Student Name</td>
            <td>Email</td>
            <td>Roll Numder</td>
            <td>Section</td>
            <td>Action</td>
        </th>
        
        {% for i in data %}
        <tr><td></td>
            <td>{{i.name}}</td>
            <td>{{i.email}}</td>
            <td>{{i.roll_number}}</td>
            <td>{{i.section}}</td>
            <td><a href="{% url 'update' i.id %}
button>Update</button></a>
            <a href="#"><button>Delete</button></a></td>
        </tr>
        {% endfor %}  
    </table>
</body>
</html>

Output for Update operation:

output 1 for UPDATE operation in CRUD operations in Django without form
output 2 for UPDATE operation
output 3 for UPDATE operation

Delete in CRUD operations in Django without Form

views.py

def delete(request,id):
    dataget = Student.objects.get(id=id)
    dataget.delete()
    return redirect('create')

index.html

<a href="{% url 'delete' i.id %}"><button>Delete</button></a>

Output for Delete operation:

output 1 for delete operation
output 2 for delete operation
output 3 for delete operation

Also Read:

Share:

Author: Harry

Hello friends, thanks for visiting my website. I am a Python programmer. I, with some other members, write blogs on this website based on Python and Programming. We are still in the growing phase that's why the website design is not so good and there are many other things that need to be corrected in this website but I hope all these things will happen someday. But, till then we will not stop ourselves from uploading more amazing articles. If you want to join us or have any queries, you can mail me at admin@copyassignment.com Thank you