How to carry out CRUD operations in Django?

Key takeaways:

  1. Django is a Python web framework that follows the MVT (model view template) architecture and simplifies CRUD operations.

  2. The Create operation involves defining a model, running migrations, and creating views to add new records to the database.

  3. The Read operation retrieves data from the database and displays it using views and templates.

  4. The Update operation allows modification of existing records by creating views to handle form submissions and updates.

  5. The Delete operation involves permanently removing records from the database with views and confirmation templates.

  6. Implementing CRUD in Django is straightforward but may require additional security and authentication features in real-world scenarios.

Django is a widely-used Python web framework that enables rapid and straightforward web app development without the installation or dependency issues common in other frameworks. Its architecture follows the MVT (model view template) pattern, making it simple to perform CRUD (create, read, update, delete) operations. These operations are crucial when working with databases and building online applications.

Here’s a detailed guide on how to execute CRUD operations:

Create operation

In the Create operation, we make a new entry in the database. Follow these steps to add new records to the database:

  • Define a model: Create a model class in the Django application file, and each attribute of this class will behave as a database field.

# models.py
from django.db import models
class Student(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField(unique=True)
cgpa = models.DecimalField(max_digits=4, decimal_places=2)
def __str__(self):
return self.name
Building a model class
  • Run migrations: Run the following command to make a database table.

Python manage.py makemigrations
Python manage.py migrate
Run migrations
  • Define a view: Create a view in which queries are made to create desired data in the database.

# Create view
def student_create(request):
if request.method == 'POST':
form = StudentForm(request.POST)
if form.is_valid():
form.save()
return redirect('student_list')
else:
form = StudentForm()
return render(request, 'students/student_form.html', {'form': form})
Defining a view to create data in the database

Read operation

The Read operation allows to read or retrieve data from the tables in the database. Follow these steps to read records from the database:

  • Define a view: Create a view in which queries are made to retrieve desired data from the database.

from django.shortcuts import render
# Create your views here.
from django.shortcuts import render, redirect, get_object_or_404
from .models import Student
from .forms import StudentForm
# List view
def student_list(request):
students = Student.objects.all()
return render(request, 'students/student_list.html', {'students': students})
Defining a view to read data from the database
  • Make a template: Make an HTML template to display the retrieved list.

<!DOCTYPE html>
<html>
<head>
<title>Student List</title>
</head>
<body>
<h1>Student List</h1>
<a href="{% url 'student_create' %}">Add Student</a>
<table border="1">
<tr>
<th>Name</th>
<th>Email</th>
<th>CGPA</th>
<th>Actions</th>
</tr>
{% for student in students %}
<tr>
<td>{{ student.name }}</td>
<td>{{ student.email }}</td>
<td>{{ student.cgpa }}</td>
<td>
<a href="{% url 'student_update' student.id %}">Update</a>
<a href="{% url 'student_delete' student.id %}">Delete</a>
</td>
</tr>
{% endfor %}
</table>
</body>
</html>
Page for showing a student list in Django

Update operation

The update operation is used to make modifications to the database. Follow these steps to update records in the database:

  • Define a view: Make a view that retrieves the record that needs to be modified, then makes a form with its data and handles form submissions.

# views.py
def student_update(request, id):
student = get_object_or_404(Student, id=id)
if request.method == 'POST':
form = StudentForm(request.POST, instance=student)
if form.is_valid():
form.save()
return redirect('student_list')
else:
form = StudentForm(instance=student)
return render(request, 'students/student_form.html', {'form': form})
Defining a view to update data in the database
  • Make a template: Make an HTML template to update the retrieved record.

<!DOCTYPE html>
<html>
<head>
<title>Add/Update Student</title>
</head>
<body>
<h1>{% if form.instance.pk %}Update{% else %}Add{% endif %} Student</h1>
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Save</button>
</form>
<a href="{% url 'student_list' %}">Back to Student List</a>
</body>
</html>
Confirmation page for adding/updating a student record in Django

Delete operation

The Delete operation is used to delete an entity from the database permanently. Follow these steps to delete the record from the database:

  • Define a view: Make a view that retrieves the record to be deleted and then manages the deletion process.

# views.py
# Delete view
def student_delete(request, id):
student = get_object_or_404(Student, id=id)
if request.method == 'POST':
student.delete()
return redirect('student_list')
return render(request, 'students/student_confirm_delete.html', {'student': student})
Defining a view to delete data from the database
  • Make a template: Make an HTML template to confirm the deletion process.

<!DOCTYPE html>
<html>
<head>
<title>Delete Student</title>
</head>
<body>
<h1>Are you sure you want to delete {{ student.name }}?</h1>
<form method="POST">
{% csrf_token %}
<button type="submit">Confirm Delete</button>
</form>
<a href="{% url 'student_list' %}">Cancel</a>
</body>
</html>
Confirmation page for deleting a student record in Django

Note: These are easy example code to understand the CRUD process in Django. A real-world application may require more complicated scenarios, security mechanisms, and user authentication.

Try it yourself

We've set CRUD operations in simple django application. Press the "Run" button and then click on the link in the below widget to perform CRUD operations.

SQLite format 3@  $">$.O|��
��d!��B
�
�
w
4��V��P3%Astudents0001_initial2024-10-02 11:47:07.7603173%Asessions0001_initial2024-10-02 11:47:07.758563HWAauth0012_alter_user_first_name_max_length2024-10-02 11:47:07.755412@GAauth0011_update_proxy_permissions2024-10-02 11:47:07.748373CMAauth0010_alter_group_name_max_length2024-10-02 11:47:07.743821GUAauth0009_alter_user_last_name_max_length2024-10-02 11:47:07.735205F
SAauth0008_alter_user_username_max_length2024-10-02 11:47:07.726069K]Aauth0007_alter_validators_add_error_messages2024-10-02 11:47:07.717056AIAauth0006_require_contenttypes_00022024-10-02 11:47:07.713057B
KAauth0005_alter_user_last_login_null2024-10-02 11:47:07.712078@	GAauth0004_alter_user_username_opts2024-10-02 11:47:07.704580CMAauth0003_alter_user_email_max_length2024-10-02 11:47:07.699957HWAauth0002_alter_permission_name_max_length2024-10-02 11:47:07.693627H%GAcontenttypes0002_remove_content_type_name2024-10-02 11:47:07.687337IWAadmin0003_logentry_add_action_flag_choices2024-10-02 11:47:07.675573AGAadmin0002_logentry_remove_auto_add2024-10-02 11:47:07.6706090%Aadmin0001_initial2024-10-02 11:47:07.663711/%Aauth0001_initial2024-10-02 11:47:07.6584587%%Acontenttypes0001_initial2024-10-02 11:47:07.645330
�a���v��a-	students_student+auth_permission
!auth_groupauth_user3django_content_type-django_admin_log/django_migrations
v������vstudentsstudentsessionssession%#contenttypescontenttype
authuserauthgroup!authpermission	adminlogentry
u������ustudentsstudentsessionssession%#contenttypescontenttypeauthuser
authgroup!authpermissionadminlogentry

�������mWG4!������n\G2

�
�
�%view_student)delete_student)change_student#add_student%view_session)delete_session)change_session#add_session-view_contenttype1delete_contenttype1change_contenttype+add_contenttypeview_user#delete_user#change_useradd_user
!view_group%delete_group%change_group
add_group	+view_permission/delete_permission/change_permission)add_permission	'view_logentry	+delete_logentry	+change_logentry	%	add_logentry







]����������������������{uoic]

						






��$�	��
w�W��	?E<��O��=���~--�/tabledjango_admin_logdjango_admin_logCREATE TABLE "django_admin_log" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "object_id" text NULL, "object_repr" varchar(200) NOT NULL, "action_flag" smallint unsigned NOT NULL CHECK ("action_flag" >= 0), "change_message" text NOT NULL, "content_type_id" integer NULL REFERENCES "django_content_type" ("id") DEFERRABLE INITIALLY DEFERRED, "user_id" integer NOT NULL REFERENCES "auth_user" ("id") DEFERRABLE INITIALLY DEFERRED, "action_time" datetime NOT NULL)�JoA�qindexauth_user_user_permissions_permission_id_1fbb5f2cauth_user_user_permissionsCREATE INDEX "auth_user_user_permissions_permission_id_1fbb5f2c" ON "auth_user_user_permissions" ("permission_id")�?k-�sindexauth_user_groups_user_id_group_id_94350c0c_uniqauth_user_groupsCREATE UNIQUE INDEX "auth_user_groups_user_id_group_id_94350c0c_uniq" ON "auth_user_groups" ("user_id", "group_id")�:g9�aindexauth_group_permissions_permission_id_84c5c92eauth_group_permissionsCREATE INDEX "auth_group_permissions_permission_id_84c5c92e" ON "auth_group_permissions" ("permission_id")�+]9�Mindexauth_group_permissions_group_id_b120cbf9auth_group_permissionsCREATE INDEX "auth_group_permissions_group_id_b120cbf9" ON "auth_group_permissions" ("group_id")�0--�tableauth_user_groupsauth_user_groupsCREATE TABLE "auth_user_groups" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "user_id" integer NOT NULL REFERENCES "auth_user" ("id") DEFERRABLE INITIALLY DEFERRED, "group_id" integer NOT NULL REFERENCES "auth_group" ("id") DEFERRABLE INITIALLY DEFERRED)&P�w�	A�/indexauth_user_user_permissions_user_id_permission_id_14a6b632_uniqauth_user_user_permissionsCREATE UNIQUE INDEX "auth_user_user_permissions_user_id_permission_id_14a6b632_uniq" ON "auth_user_user_permissions" ("user_id", "permission_id")�Q-�5indexauth_user_groups_group_id_97559544auth_user_groupsCREATE INDEX "auth_user_groups_group_id_97559544" ON "auth_user_groups" ("group_id")�N99�7tableauth_group_permissionsauth_group_permissions	CREATE TABLE "auth_group_permissions" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "group_id" integer NOT NULL REFERENCES "auth_group" ("id") DEFERRABLE INITIALLY DEFERRED, "permission_id" integer NOT NULL REFERENCES "auth_permission" ("id") DEFERRABLE INITIALLY DEFERRED)�8cA�Yindexauth_user_user_permissions_user_id_a95ead1bauth_user_user_permissionsCREATE INDEX "auth_user_user_permissions_user_id_a95ead1b" ON "auth_user_user_permissions" ("user_id")�O-�1indexauth_user_groups_user_id_6a12ed8bauth_user_groupsCREATE INDEX "auth_user_groups_user_id_6a12ed8b" ON "auth_user_groups" ("user_id")�j�9�#indexauth_group_permissions_group_id_permission_id_0cd325b0_uniqauth_group_permissionsCREATE UNIQUE INDEX "auth_group_permissions_group_id_permission_id_0cd325b0_uniq" ON "auth_group_permissions" ("group_id", "permission_id")�XAA�;tableauth_user_user_permissionsauth_user_user_permissions
CREATE TABLE "auth_user_user_permissions" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "user_id" integer NOT NULL REFERENCES "auth_user" ("id") DEFERRABLE INITIALLY DEFERRED, "permission_id" integer NOT NULL REFERENCES "auth_permission" ("id") DEFERRABLE INITIALLY DEFERRED)P++Ytablesqlite_sequencesqlite_sequenceCREATE TABLE sqlite_sequence(name,seq)�Y//�atabledjango_migrationsdjango_migrationsCREATE TABLE "django_migrations" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "app" varchar(255) NOT NULL, "name" varchar(255) NOT NULL, "applied" datetime NOT NULL)

G�
<	���m�Y���C�"��?5S-indexsqlite_autoindex_students_student_1students_student"�3S)�9indexdjango_session_expire_date_a5c62663django_session CREATE INDEX "django_session_expire_date_a5c62663" ON "django_session" ("expire_date")�61))�'tabledjango_sessiondjango_session
CREATE TABLE "django_session" ("session_key" varchar(40) NOT NULL PRIMARY KEY, "session_data" text NOT NULL, "expire_date" datetime NOT NULL);2O)indexsqlite_autoindex_django_session_1django_session10Eindexsqlite_autoindex_auth_user_1auth_user�-!!�mtableauth_groupauth_groupCREATE TABLE "auth_group" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "name" varchar(150) NOT NULL UNIQUE)�3.G!indexsqlite_autoindex_auth_group_1auth_group
�2�*/�#tableauth_userauth_userCREATE TABLE "auth_user" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "password" varchar(128) NOT NULL, "last_login" datetime NULL, "is_superuser" bool NOT NULL, "username" varchar(150) NOT NULL UNIQUE, "last_name" varchar(150) NOT NULL, "email" varchar(254) NOT NULL, "is_staff" bool NOT NULL, "is_active" bool NOT NULL, "date_joined" datetime NOT NULL, "first_name" varchar(150) NOT NULL)�$$]+�Mindexauth_permission_content_type_id_2f476e4bauth_permissionCREATE INDEX "auth_permission_content_type_id_2f476e4b" ON "auth_permission" ("content_type_id")�S#y+�indexauth_permission_content_type_id_codename_01ab375a_uniqauth_permissionCREATE UNIQUE INDEX "auth_permission_content_type_id_codename_01ab375a_uniq" ON "auth_permission" ("content_type_id", "codename")�%"++�tableauth_permissionauth_permissionCREATE TABLE "auth_permission" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "content_type_id" integer NOT NULL REFERENCES "django_content_type" ("id") DEFERRABLE INITIALLY DEFERRED, "codename" varchar(100) NOT NULL, "name" varchar(255) NOT NULL)�H!o3�{indexdjango_content_type_app_label_model_76bd3d3b_uniqdjango_content_typeCREATE UNIQUE INDEX "django_content_type_app_label_model_76bd3d3b_uniq" ON "django_content_type" ("app_label", "model")�I 33�9tabledjango_content_typedjango_content_typeCREATE TABLE "django_content_type" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "app_label" varchar(100) NOT NULL, "model" varchar(100) NOT NULL)�O-�1indexdjango_admin_log_user_id_c564eba6django_admin_logCREATE INDEX "django_admin_log_user_id_c564eba6" ON "django_admin_log" ("user_id")�(_-�Qindexdjango_admin_log_content_type_id_c4bce8ebdjango_admin_logCREATE INDEX "django_admin_log_content_type_id_c4bce8eb" ON "django_admin_log" ("content_type_id");�[4--�itablestudents_studentstudents_student!CREATE TABLE "students_student" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "name" varchar(100) NOT NULL, "email" varchar(254) NOT NULL UNIQUE, "cgpa" decimal NOT NULL)





����b:���rN.
�
�
�
�
T
#����`>��"%-view_studentCan view student&)1delete_studentCan delete student&)1change_studentCan change student #+add_studentCan add student"%-view_sessionCan view session&)1delete_sessionCan delete session&)1change_sessionCan change session #+add_sessionCan add session+-7view_contenttypeCan view content type/1;delete_contenttypeCan delete content type/1;change_contenttypeCan change content type)+5add_contenttypeCan add content type'view_userCan view user #+delete_userCan delete user #+change_userCan change user
%add_userCan add user!)view_groupCan view group"%-delete_groupCan delete group"
%-change_groupCan change group	'add_groupCan add group(+3view_permissionCan view permission,/7delete_permissionCan delete permission,/7change_permissionCan change permission&)1add_permissionCan add permission$	'1view_logentryCan view log entry(	+5delete_logentryCan delete log entry(	+5change_logentryCan change log entry"	%/add_logentryCan add log entry



�1
�
A simple django application to perform CRUD operations on student record

Conclusion

Django is a highly efficient framework for building web applications that interact with databases through CRUD operations.

By leveraging the MVT architecture, developers can easily create, read, update, and delete records. The provided step by step guide demonstrates how to perform each operation in a Django application, laying the foundation for more complex use cases in real-world applications.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


How to write CRUD operations in Django?

To write CRUD operations in Django:

  • Create: Define a model, run migrations, and create a view to add data.
  • Read: Create a view to retrieve data and a template to display it.
  • Update: Create a view to fetch the record, display it in a form, and handle updates.
  • Delete: Create a view to delete records with a confirmation template.

What is the difference between REST API and CRUD API?

A CRUD API focuses on basic operations (Create, Read, Update, Delete) for managing data in a database. A REST API is a broader architecture for building APIs, using HTTP methods (GET, POST, PUT, DELETE) to perform CRUD operations while adhering to REST principles like statelessness and resource representation.


Free Resources

Copyright ©2025 Educative, Inc. All rights reserved