article

Saturday, May 14, 2022

Python Django Mysql CRUD (Create, Read, Update and Delete) with Jquery Ajax

Python Django Mysql CRUD (Create, Read, Update and Delete) with Jquery Ajax

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 Member(models.Model):
    firstname = models.CharField(max_length=50)
    lastname = models.CharField(max_length=50)
   
    class Meta:  
        db_table = "tbl_member"
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

Creating View
myapp/views.py
 
//myapp/views.py
from django.shortcuts import render, redirect
from myapp.models import Member
 
# Create your views here.
def index(request):
    return render(request, 'index.html')
 
def create(request):
    member = Member(firstname=request.POST['firstname'], lastname=request.POST['lastname'])
    member.save()
    return redirect('/')
 
def read(request):
    members = Member.objects.all()
    context = {'members': members}
    return render(request, 'result.html', context)
 
def edit(request, id):
    members = Member.objects.get(id=id)
    context = {'member': members}
    return render(request, 'edit.html', context)
 
 
def update(request, id):
    member = Member.objects.get(id=id)
    member.firstname = request.POST['firstname']
    member.lastname = request.POST['lastname']
    member.save()
    return redirect('/')
 
 
def delete(request, id):
    member = Member.objects.get(id=id)
    member.delete()
    return redirect('/')
Template

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
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js

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

myapp/templates/index.html
//myapp/templates/index.html
{% extends 'base.html' %}
{% block body %}
<form class="form-inline">
    {% csrf_token %}
    <div class="mb-3">
        <label>Firstname</label>
        <input type="text" id="firstname" class="form-control" style="width:30%;" required="required"/>
    </div>    
    <div class="mb-3">
        <label>Lastname</label>
        <input type="text" id="lastname" class="form-control" style="width:30%;" required="required"/>
    </div>
    <div class="mb-3">    
        <button type="button" id="create" class="btn btn-primary">Create</button>
    </div>
</form>
<br />
<div id="result"></div>
{% endblock %}
myapp/templates/base.html
//myapp/templates/base.html
<!DOCTYPE html>
<html lang="en">
<head>
{% load static %}
<meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"/>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
</head>
<body>
    <div class="container">
        <header>
            <h1>Python Django Mysql CRUD (Create, Read, Update and Delete) with Jquery Ajax</h1>
        </header>
        <hr>
        <main>
            {% block body %}
            {% endblock %}
        </main>
        <hr>
    </div>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script src="{% static 'js/script.js' %}"></script>
</body>
</html>
myapp/templates/edit.html
//myapp/templates/edit.html
{% extends 'base.html' %}
{% block body %}
    <form>
        {% csrf_token %}
        <input type="hidden" id="member_id" value="{{ member.id }}"/>
        <div class="mb-3">
            <label>Firstname</label>
            <input type="text" id="firstname" value="{{ member.firstname }}" class="form-control" required="required"/>
        </div>
        <div class="mb-3">
            <label>Lastname</label>
            <input type="text" id="lastname" value="{{ member.lastname }}" class="form-control" required="required"/>
        </div>
        <div class="mb-3">
            <button type="button" id="update" class="btn btn-warning">Update</button>
        </div>
    </form>
{% endblock %}
myapp/templates/result.html
//myapp/templates/result.html
<table class="table table-bordered">
    <thead class="alert-success">
        <tr>
            <th>Firstname</th>
            <th>Lastname</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
        {% for member in members %}
        <tr>
            <td>{{ member.firstname }}</td>
            <td>{{ member.lastname }}</td>
            <td><center>
                <a class="btn btn-warning edit" name="{{ member.id }}">Edit</a> 
                <a class="btn btn-danger delete" name="{{ member.id }}">Delete</a></center>
            </td>
        </tr>
        {% endfor %}
    </tbody>
</table>
myapp/static/js/script.js
//myapp/static/js/script.js
$(document).ready(function(){
    if($('#result') != null){
        Read();
    }
    $('#create').on('click', function(){
        $firstname = $('#firstname').val();
        $lastname = $('#lastname').val();
 
        if($firstname == "" || $lastname == ""){
            alert("Please complete the required field");
        }else{
            $.ajax({
                url: 'create/',
                type: 'POST',
                data: {
                    firstname: $firstname,
                    lastname: $lastname,
                    csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
                },
                success: function(){
                    Read();
                    $('#firstname').val('');
                    $('#lastname').val('');
                    alert("New Member Successfully Added");
                }
            });
        }
    });
 
    $(document).on('click', '.edit', function(){
        $id = $(this).attr('name');
        window.location = "edit/" + $id;
    });
 
    $('#update').on('click', function(){
        $firstname = $('#firstname').val();
        $lastname = $('#lastname').val();
 
        if($firstname == "" || $lastname == ""){
            alert("Please complete the required field");
        }else{
            $id = $('#member_id').val();
            $.ajax({
                url: 'update/' + $id,
                type: 'POST',
                data: {
                    firstname: $firstname,
                    lastname: $lastname,
                    csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
                },
                success: function(){
                    window.location = '/';
                    alert('Updated!');
                }
            });
        }
 
    });
 
    $(document).on('click', '.delete', function(){
        $id = $(this).attr('name');
        $.ajax({
            url: 'delete/' + $id,
            type: 'POST',
            data: {
                csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
            },
            success: function(){
                Read();
                alert("Deleted!");
            }
        });
    });
 
});
 
function Read(){
    $.ajax({
        url: 'read/',
        type: 'POST',
        async: false,
        data:{
            res: 1,
            csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
        },
        success: function(response){
            $('#result').html(response);
        }
    });
}
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('create/',views.create, name='create'),
    path('read/',views.read, name='read'),
    path('edit/<id>',views.edit, name='edit'),
    path('edit/update/<id>',views.update, name='update'),
    path('delete/<id>',views.delete, name='delete'),
]
Run : C:\django\devproject>python manage.py runserver

Related Post