Creating a CRUD application using Django with MySQL database
In this tutorial, we will create a CRUD (Create, Read, Update, Delete) application using Django with a MySQL database.It helps to manage data in web application.
1. Create a Django Project
Run the following command to create a new Django project.
django-admin startproject demo_crud
2. Create a Django App
Create Django App Inside your project, using the following command.
python manage.py startapp crud
Project Folder Structure
Django creates a new project and App folder, with following content.
3. Register the app name inside the project (demo_crud) settings.py file
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crud', #app name ]
4. Install MySQL Client
Install mysqlclient using the following command.
pip install mysqlclient
5. MySQL Database Setup
Create a database db_crud in mysql, and configure into the settings.py file of django project(demo_crud).
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'db_crud', 'USER': 'root', 'PASSWORD': '', 'HOST':'localhost', 'PORT':'3306', } }
6. Set the App URLs in the Project
Open demo_crud/urls.py inside the project directory and add the following code
from django.contrib import admin from django.urls import path,include urlpatterns = [ path('',include('crud.urls')) ]
7. Create a Model
Create the database model for storing customers. Write the following code into crud/models.py file.
from django.db import models class Customer(models.Model): cid = models.AutoField(primary_key=True) cname = models.CharField(max_length=50) cemail = models.CharField(max_length=50) ccity = models.CharField(max_length=50) class Meta: db_table = "tbl_customer"
8.Make Migration
Migration is a way of apply and synchronize changes in the database schema based on your models.
Create Migration Files
Run the makemigrations command to generate new migration files.
python manage.py makemigrations
Apply Migrations
Run the migrate command to apply migrations to your database.
python manage.py migrate
After migration is applied it reflect the migration into the database. List of tables created after migrate command as shown on image below
9. Create View Functions
Write the following code into crud/views.py file.
from django.shortcuts import render,redirect from .models import Customer # Create a new customer and list all customers def index(request): data = {} if request.method == "POST": a = request.POST["customer_name"] b = request.POST["customer_email"] c = request.POST["customer_city"] obj=Customer(cname=a,cemail=b,ccity=c) obj.save() data["record"] = Customer.objects.all() return render(request,"index.html",data) # Update an existing customer def customer_edit(request,id): data = {} if request.method=='POST': a = request.POST["customer_name"] b = request.POST["customer_email"] c = request.POST["customer_city"] obj=Customer.objects.get(cid=id) obj.cname=a obj.cemail=b obj.ccity=c obj.save() data["record"] = Customer.objects.get(cid=id) return render(request,"customer_edit.html",data) # Delete a customer def customer_delete(request,id): Customer.objects.get(cid=id).delete() return redirect(index)
10. Creating URLs
Open urls.py file in crud folder and provide URL patterns to map with views function.
from django.urls import path from django.views.generic import RedirectView from .import views urlpatterns = [ path('', RedirectView.as_view(pattern_name='index', permanent=False)), #Redirect to index path('index',views.index,name="index"), path('customer_edit/<int:id>',views.customer_edit,name="customer_edit"), path('customer_delete/<int:id>',views.customer_delete,name="customer_delete") ]
11. Create Templates
Create a templates folder inside the crud app and create two (index.html, customer_edit.html) html files inside the directory
// index.html<!DOCTYPE html> <html lang="en"> <head> <title>Django with MySQL - CRUD</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div class="container mt-5"> <nav aria-label="breadcrumb"> <ol class="breadcrumb"> <li class="breadcrumb-item active">Home</li> </ol> </nav> <div class="row mt-5"> <div class="col-md-5"> <div class="card p-3"> <div class="card-body"> <h4>Add Customer</h4><hr> <form method="POST" action=""> {% csrf_token %} <div class="mb-3"> <label class="form-label">Name</label> <input type="text" class="form-control form-control-sm" name="customer_name" required> </div> <div class="mb-3"> <label class="form-label">Email Id</label> <input type="email" class="form-control form-control-sm" name="customer_email" required> </div> <div class="mb-3"> <label class="form-label">City</label> <input type="text" class="form-control form-control-sm" name="customer_city" required> </div> <input type="submit" value="Save Customer" class="btn btn-primary btn-sm"> </form> </div> </div> </div> <div class="col-md-7"> <table class="table table-bordered table-striped"> <thead> <tr> <th>Sno</th> <th>Name</th> <th>Email</th> <th>City</th> <th>Edit</th> <th>Delete</th> </tr> </thead> <tbody> {% for row in record %} <tr> <td>{{forloop.counter}}</td> <td>{{row.cname}}</td> <td>{{row.cemail}}</td> <td>{{row.ccity}}</td> <td><a href="customer_edit/{{row.cid}}" class="btn btn-warning btn-sm">Edit</a></td> <td><a href="customer_delete/{{row.cid}}" class="btn btn-danger btn-sm">Delete</a></td> </tr> {% endfor %} </tbody> </table> </div> </div> </div> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <title>Django with MySQL - CRUD</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div class="container mt-5"> <nav aria-label="breadcrumb"> <ol class="breadcrumb"> <li class="breadcrumb-item"><a href="/index">Home</a></li> <li class="breadcrumb-item">Edit Customer</li> </ol> </nav> <div class="row"> <div class="col-md-5 mt-5"> <div class="card p-3"> <div class="card-body"> <h4>Edit Customer</h4><hr> <form method="POST" action=""> {% csrf_token %} <div class="mb-3"> <label class="form-label">Name</label> <input type="text" class="form-control form-control-sm" name="customer_name" value='{{record.cname}}' required> </div> <div class="mb-3"> <label class="form-label">Email Id</label> <input type="email" class="form-control form-control-sm" name="customer_email" value='{{record.cemail}}' required> </div> <div class="mb-3"> <label class="form-label">City</label> <input type="text" class="form-control form-control-sm" name="customer_city" value='{{record.ccity}}' required> </div> <input type="submit" value="Update Customer" class="btn btn-primary btn-sm"> </form> </div> </div> </div> </div> </div> </body> </html>
12. Run the Server
Run the Project using the following command.
python manage.py runserver
D:\Blog\crudoperation\demo_crud>python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. August 22, 2024 - 11:54:04 Django version 4.2.8, using settings 'demo_crud.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK.
Output
Add and List Customers
Edit Customer
Add and List Customers
Edit Customer