Django Application to Perform CRUD Operations

Nov. 15, 2022


0
5 min read
875

CRUD operations in a Django application mean creating, reading, updating, and deleting operations on the database. An admin user can do all these operations using the Django admin site. But in this article, we will learn how to implement it within the website using the Django ModelForm.

Let’s get started.

Project Setup

First, we need to create a Django project. Let’s install Django:

pip install Django

Then create a Django project named crud:

django-admin startproject crud

Within the project, we will create a separate app named enroll because the application will perform CRUD operations on a student information database.

python manage.py startapp enroll

Now we need to add the enroll app in crud/settings.py. Add 'enroll' to the INSTALLED_APPS list:

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'enroll', #New
]

Creating the Student Model

Inside enroll/models.py we will create our Student model.

from django.db import models


# Create your models here.
class Student(models.Model):
    name = models.CharField(max_length=70)
    email = models.EmailField(max_length=70)
    password = models.CharField(max_length=70)

We need to register this model in admin.py to see it on the admin site.

from django.contrib import admin
from . models import Student
# Register your models here.

@admin.register(Student)
class StudentModel(admin.ModelAdmin):
    list_display = ('id', 'name', 'email', 'password')

Now make migrations to the database and create a superuser to gain admin access using the following commands:

python manage.py makemigrations
python manage.py migrate

Create a super user using the following commands:

python manage.py createsuperuser

Creating the Forms

We will create a forms.py file and write the code of our form in it.

Inside enroll/forms.py 

from django import forms
from django.forms import widgets
from . models import Student

class StudentForm(forms.ModelForm):
    class Meta:
        model = Student
        fields = ('name', 'email', 'password')
        widgets = {
            'name':forms.TextInput(attrs={'class':'form-control'}),
            'email':forms.EmailInput(attrs={'class':'form-control'}),
            'password':forms.PasswordInput(render_value=True ,attrs={'class':'form-control'}),
        }
        labels = {
            'name':'Enter Name',
            'email':'Enter Email',
            'password':'Enter Password',
        }

Creating the Views

Inside enroll/views.py we will create view functions:

from django.shortcuts import render
from . models import Student
from . forms import StudentForm
from django.http import HttpResponseRedirect
# Create your views here.

#this is to insert and show data
def home(request):
    if request.method == "POST":
        fm = StudentForm(request.POST)
        if fm.is_valid():
            nm = fm.cleaned_data.get('name')
            em = fm.cleaned_data.get('email')
            pd = fm.cleaned_data.get('password')
            data = Student(name=nm, email=em, password=pd)
            data.save()
            fm = StudentForm()
    else:
        fm = StudentForm()
    stud = Student.objects.all()
    return render(request, 'enroll/home.html', {'form':fm, 'stu':stud})

#This is for deleting data
def delete(request, id):
    if request.method == "POST":
            d = Student.objects.get(pk=id)
            d.delete()
            return HttpResponseRedirect('/')

#This is for data update
def update(request, id):
    if request.method == "POST":
        up = Student.objects.get(pk=id)
        fm = StudentForm(request.POST, instance=up)
        if fm.is_valid():
            up.save()
    else:
        up = Student.objects.get(pk=id)
        fm = StudentForm(instance=up)
    return render(request, 'enroll/update.html', {'form': fm, 'id':id})

Creating the URL patterns

Then we will create URL patterns for each view inside enroll/urls.py:

from django.urls import path
from . import views
import enroll
urlpatterns = [
    path('', views.home, name='home'),
    path('delete/<int:id>/', views.delete, name='delete'),
    path('update/<int:id>/', views.update, name='update')
]

Creating Templates 

Then in the enroll app directory, we will create a folder named templates. And inside the templates/enroll folder, we will create an HTML file named home.html.

<!DOCTYPE html>
<html lang="en">
  <head>
    {% load static %}
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <!-- this offline static file 👇 -->
    <!-- <link rel="stylesheet" href="{% static 'enroll/css/bootstrap.css' %}"> -->
    <!-- CSS only -->
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css"
      rel="stylesheet"
      integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi"
      crossorigin="anonymous"
    />
    <title>Home</title>
  </head>
  <body>
    <div class="form-group container">
      <h2 class="alert alert-danger text-center">
        CRUD Project based on ModelForm
      </h2>
      <h3 class="alert alert-primary text-left">Enter Details</h3>
      <form action="" method="POST">
        {% csrf_token %} {{form.as_p}}
        <input class="btn btn-success" type="submit" value="Add" />
      </form>
    </div>
    <br />
    <div class="container">
      <table class="table">
        <thead>
          <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Email</th>
            <th>Password</th>
            <th>Action</th>
          </tr>
        </thead>
        <tbody>
          {% for st in stu %}
          <tr class="table-info">
            <th scope="row">{{st.id}}</th>
            <td>{{st.name}}</td>
            <td>{{st.email}}</td>
            <td>{{st.password}}</td>
            <td>
              <a href="{% url 'update' st.id %}" class="btn btn-warning"
                >Edit</a
              >
              <form
                action="{% url 'delete' st.id %}"
                method="post"
                class="d-inline"
              >
                {% csrf_token %}
                <input class="btn btn-danger" type="submit" value="Delete" />
              </form>
            </td>
          </tr>
          {% endfor %}
        </tbody>
      </table>
    </div>

    <!-- JavaScript Bundle with Popper -->
    <script
      src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"
      integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3"
      crossorigin="anonymous"
    ></script>
    <!-- this offline static file 👇 -->
    <!-- <script src="{% static 'enroll/js/jquery.js' %}"></script>
    <script src="{% static 'enroll/js/popper.js' %}"></script>
    <script src="{% static 'enroll/js/bootstrap.js' %}"></script> -->
  </body>
</html>

We will create another template named update.html.

<!DOCTYPE html>
<html lang="en">
  <head>
    {% load static %}
    <!-- CSS only -->
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css"
      rel="stylesheet"
      integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi"
      crossorigin="anonymous"
    />
    <!-- this offline static file 👇 -->
    <!-- <link rel="stylesheet" href="{% static 'enroll/css/bootstrap.css' %}"> -->
    <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>update</title>
  </head>
  <body>
    <div class="form-group container">
      <form action="" class="" method="POST">
        <h3 class="alert alert-primary text-center">Edit Details</h3>
        {% csrf_token %} {{form.as_p}}
        <input class="btn btn-success" type="submit" value="Update" />
        <a class="btn btn-danger" href="{% url 'home' %}">Back to Home</a>
      </form>
    </div>
    <!-- JavaScript Bundle with Popper -->
    <script
      src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"
      integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3"
      crossorigin="anonymous"
    ></script>
    <!-- this offline static file 👇 -->
    <!-- <script src="{% static 'enroll/js/jquery.js' %}"></script>
    <script src="{% static 'enroll/js/popper.js' %}"></script>
    <script src="{% static 'enroll/js/bootstrap.js' %}"></script> -->
  </body>
</html>

Creating static file

In this we have also used static file you can see the static file of bootstrap. You can create your own static file also you have to use static folder inside enroll app example:

See Results:

Update data:

django projects CRUD Appreciate you stopping by my post! 😊

Add a comment


Note: If you use these tags, write your text inside the HTML tag.
Login Required
Author's profile
Profile Image

Abdulla Fajal

Django Developer

With 'espere.in' under my care, I, Abdulla Fajal, graciously invite your insights and suggestions, as we endeavour to craft an exquisite online experience together.