Step 1:- models.py file code:-
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"
step 2:-admin.py file code:-
from django.contrib import admin
from myapp.models import Member
# Register your models here.
admin.site.register(Member)
step 3:- views.py file code :-
from django.shortcuts import render, redirect
from myapp.models import Member
from django.http import JsonResponse
# 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 JsonResponse({'status':'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 JsonResponse({'status':'Update'})
def delete(request, id):
member = Member.objects.get(id=id)
member.delete()
return JsonResponse({'status':'Delete'})
step 4:-urls.py file code of project folder :-
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('myapp/', include('myapp.urls')),
]
step 5:- urls.py file code of myapp folder :-
from django.urls import path
from myapp import views
urlpatterns = [
path('', views.index, name='index'),
path('create/',views.create, name='create'),
path('read/',views.read, name='read'),
path('edit/<int:id>',views.edit, name='edit'),
path('edit/update/<int:id>',views.update, name='update'),
path('delete/<id>',views.delete, name='delete'),
]
step 6:- create "templates" folder inside your app folder :-
base.html file code:-
<!DOCTYPE html>
<html lang="en">
<head>
{% load static %}
<meta charset="UTF-8" name="viewport" content="width=device-width, initialscale=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.mi
n.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>
index.html file code:-
//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 %}
edit.html file code:-
//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 %}
result.html file code :-
//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 }}
{{member.id}}
</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>
now create static folder inside your app folder and create js folder inside static and
create script.js file code:-
//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(data){
Read();
$('#firstname').val('');
$('#lastname').val('');
if(data.status=='Save')
{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(data){
if(data.status=='Update')
{
alert("Successfully updated");
window.location = '../';
}
}
});
}
});
$(document).on('click', '.delete', function(){
$id = $(this).attr('name');
$.ajax({
url: 'delete/' + $id,
type: 'POST',
data: {
csrfmiddlewaretoken:
$('input[name=csrfmiddlewaretoken]').val()
},
success: function(data){
if(data.status=='Delete')
{
alert("Successfully Deleted");
window.location = './';
}
}
});
});
});
function Read(){
$.ajax({
url: 'read/',
type: 'POST',
async: false,
data:{
res: 1,
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
},
success: function(response){
$('#result').html(response);
}
});
}
Output:-
...
Sign up here with your email
ConversionConversion EmoticonEmoticon