0% found this document useful (0 votes)
21 views12 pages

CRUD

The document discusses how to perform CRUD operations in Django using forms. It explains how to create, read, update and delete data from the database. It provides code examples for models, forms, views and templates to implement each CRUD operation.

Uploaded by

ASHUTOSH TRIVEDI
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views12 pages

CRUD

The document discusses how to perform CRUD operations in Django using forms. It explains how to create, read, update and delete data from the database. It provides code examples for models, forms, views and templates to implement each CRUD operation.

Uploaded by

ASHUTOSH TRIVEDI
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

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:


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
1
2
3
4
5
6
7
8
9
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.

2
3
4
5
6
7
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

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

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:

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.
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:

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

Change the section from C to D

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

The item with id 3 is deleted from our list.

You might also like