article

Wednesday, May 18, 2022

Django Mysql CRUD (Create Read Update Delete) with Datatables

Django Mysql CRUD (Create Read Update Delete) with Datatables

Register App myapp and
Connect to MySQL Database

devproject/settings.py
 
//devproject/settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp', #add myapp
]
      
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'django',
        'USER': 'root',
        'PASSWORD': '',
        'HOST': 'localhost',
        'PORT': '3306'
    }
}
Create Model
myapp/models.py
 
//myapp/models.py
from django.db import models

# Create your models here.
class Employee(models.Model):  
    name = models.CharField(max_length=100)  
    email = models.EmailField()  
    contact = models.CharField(max_length=15) 
  
    class Meta:  
        db_table = "tblemployee"
Make Migrations
Run the commands below to make migrations:
python manage.py makemigrations
python manage.py migrate
C:\django\devproject>python manage.py makemigrations
C:\django\devproject>python manage.py migrate

Create Forms
myapp/forms.py
 
//myapp/forms.py
from django import forms  
from myapp.models import Employee  
class EmployeeForm(forms.ModelForm):  
    class Meta:  
        model = Employee  
        fields = ['name', 'contact', 'email'] 
        widgets = { 'name': forms.TextInput(attrs={ 'class': 'form-control' }), 
            'email': forms.EmailInput(attrs={ 'class': 'form-control' }),
            'contact': forms.TextInput(attrs={ 'class': 'form-control' }),
      }
Creating View
myapp/views.py
 
//myapp/views.py
from django.shortcuts import render, redirect  
from myapp.forms import EmployeeForm  
from myapp.models import Employee  

# Create your views here.  
def addnew(request):  
    if request.method == "POST":  
        form = EmployeeForm(request.POST)  
        if form.is_valid():  
            try:  
                form.save()  
                return redirect('/')  
            except:  
                pass 
    else:  
        form = EmployeeForm()  
    return render(request,'index.html',{'form':form})  

def index(request):  
    employees = Employee.objects.all()  
    return render(request,"show.html",{'employees':employees})  

def edit(request, id):  
    employee = Employee.objects.get(id=id)  
    return render(request,'edit.html', {'employee':employee})  

def update(request, id):  
    employee = Employee.objects.get(id=id)  
    form = EmployeeForm(request.POST, instance = employee)  
    if form.is_valid():  
        form.save()  
        return redirect("/")  
    return render(request, 'edit.html', {'employee': employee})  
    
def destroy(request, id):  
    employee = Employee.objects.get(id=id)  
    employee.delete()  
    return redirect("/")  
Template

myapp/templates/index.html

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js

https://datatables.net/
DataTables is a powerful jQuery plugin for creating table listings and adding interactions to them. It provides searching, sorting and pagination without any configuration.

myapp/templates/base.html
//myapp/templates/base.html
<!DOCTYPE html>  
<html lang="en">  
<head>  
<meta charset="UTF-8">  
<title>{% block title %}{% endblock %}</title>
{% load static %}  
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"/>
<link rel = "stylesheet" type = "text/css" href = "https://cdn.datatables.net/1.12.0/css/jquery.dataTables.min.css"/>
<meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
</head> 
<body>
<div class="container">
 <div class="row">
    <h4>Django Mysql CRUD (Create Read Update Delete) with Datatables</h4> 
    {% block content %}{% endblock %}
 </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
<script src = "https://cdn.datatables.net/1.12.0/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function() {
    $('#bootstrapdatatable').DataTable({     
      "aLengthMenu": [[3, 5, 10, 25, -1], [3, 5, 10, 25, "All"]],
        "iDisplayLength": 3
       } 
    );
} );
</script>
</body> 
</html>
myapp/templates/show.html
//myapp/templates/show.html
{% extends "base.html" %}
 
{% block title %}Employee Records{% endblock title %}
 
{% block content %}
 <div class="col-md-12">
        <span><a href="/addnew" class="btn btn-primary">Add New Record</a></span>  
        <div class="table-responsive">
        <table id="bootstrapdatatable" class="table table-striped table-bordered" width="100%">
        <thead>
            <th><input type="checkbox" id="checkall" /></th>
            <th>ID</th>
            <th>Employee Name</th>
            <th>Employee Email</th>
            <th>Employee Contact</th>
            <th>Edit</th>
            <th>Delete</th>
        </thead>
        <tbody>
        {% for employee in employees %}  
            <tr>  
            <td><input type="checkbox" class="checkthis" /></td>
            <td>{{ employee.id }}</td>  
            <td>{{ employee.name }}</td>  
            <td>{{ employee.email }}</td>  
            <td>{{ employee.contact }}</td>  
            <td><a href="/edit/{{ employee.id }}" class="btn btn-primary">Edit</a></td>
            <td><a href="/delete/{{ employee.id }}" class="btn btn-danger">Delete</a></td>  
            </tr>  
        {% endfor %} 
        </tbody>
        </table>
        </div>
    </div>
{% endblock content %}
myapp/templates/index.html
//myapp/templates/index.html
{% extends "base.html" %}
 
{% block title %}Add New Employee Records{% endblock title %}
 
{% block content %}
<div class="col-md-12">    
    <form method="POST" class="post-form" action="/addnew">  
    {% csrf_token %}  
    <div class="container">  
        <div class="col-12">  
        <h3>Enter Details</h3>  
        </div>    
    
        <div class="mb-3"> 
            <label>Name:</label>  
            {{ form.name }}   
        </div> 
        <div class="mb-3"> 
            <label>Email:</label>  
            {{ form.email }}   
        </div>  
        <div class="mb-3"> 
            <label>Contact:</label>  
            {{ form.contact }}   
        </div>
        <div class="mb-3"> 
            <button type="submit" class="btn btn-primary">Submit</button>    
        </div> 
    </div>  
    </form>  
</div> 
{% endblock content %} 
myapp/templates/edit.html
//myapp/templates/edit.html
{% extends "base.html" %}
 
{% block title %}Add New Employee Records{% endblock title %}
 
{% block content %}
<div class="col-md-12">
    <form method="POST" class="post-form" action="/update/{{employee.id}}">  
    {% csrf_token %}  
    <div class="container">   
        <div class="col-12">  
            <h3>Update Details</h3>  
        </div> 
        <div class="mb-3"> 
            <label>Employee ID:</label>  
            <input type="text" class="form-control" name="id" id="id_id" required maxlength="20" value="{{ employee.id }}"/>    
        </div> 
        <div class="mb-3"> 
            <label>Name:</label>  
            <input type="text" class="form-control" name="name" id="id_name" required maxlength="100" value="{{ employee.name }}" />  
        </div> 
        <div class="mb-3"> 
            <label>Email:</label>  
            <input type="email" class="form-control" name="email" id="id_email" required maxlength="254" value="{{ employee.email }}" />  
        </div> 
        <div class="mb-3"> 
            <label>Contact:</label>  
            <input type="text" class="form-control" name="contact" id="id_contact" required maxlength="15" value="{{ employee.contact }}" />  
        </div> 
        <div class="mb-3"> 
            <button type="submit" class="btn btn-success btn-lg">Update</button>  
        </div> 
    </div>  
    </form>  
{% endblock content %}   
URL
devproject/urls.py

 
//devproject/urls.py
from django.contrib import admin
from django.urls import path
from myapp import views  

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index, name='index'),  
    path('addnew',views.addnew, name='addnew'),  
    path('edit/<int:id>', views.edit, name='edit'),  
    path('update/<int:id>', views.update, name='update'),  
    path('delete/<int:id>', views.destroy, name='destroy'),  
]
Run : C:\django\devproject>python manage.py runserver

Related Post