Django Ajax Json CRUD
Django Ajax Json CRUD
com/django/how-to-execute-crud-using-django-ajax-and-json
Let’s see the example of Python Django Ajax CRUD Operations. Ajax is a way of making web development more dynamic. Using Ajax we can load data from the server without reloading the web pages.
AJAX stands for Asynchronous Javascript and XML.
In this tutorial, you’ll learn how to do CRUD operations using Django, Ajax Form Submission and JSON. We will be using the Class Based Views Functions. CRUD operation is the most basic operation
that we perform on databases. CRUD stands for Create, Read, Update, Delete. We’ll take an example of a User Management System where we will add, update and delete users and its detail. The source
code which we are building is also available on Github – Crud Ajax Django .
Basic Configuration
In this tutorial, we are going to use JQuery for implementing Ajax requests. JQuery is Simple and Easy to learn.
base.html
{% load static %}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>{% block title %}Title{% endblock title %}</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="a
{% block stylesheet %}{% endblock stylesheet %}
</head>
<body>
<main>
{% block content %}
{% endblock content %}
</main>
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
<script src='https://code.jquery.com/jquery-3.2.1.min.js'></script>
<script src='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js'></script>
{% block javascript %}
{% endblock javascript%}
</body>
</html>
I am also using Bootstrap for a beautiful user interface. For JQuery and Bootstrap, we are using CDN’s.
# models.py
1 of 9 3/22/20, 10:59 PM
Django Ajax CRUD - Execute CRUD Operations - Django https://studygyaan.com/django/how-to-execute-crud-using-django-ajax-and-json
class CrudUser(models.Model):
name = models.CharField(max_length=30, blank=True)
address = models.CharField(max_length=100, blank=True)
age = models.IntegerField(blank=True, null=True)
Let’s get started by initially loading all user details. For that, we are going to use ListView.
# Views.py
class CrudView(ListView):
model = CrudUser
template_name = 'crud_ajax/crud.html'
context_object_name = 'users'
# urls.py
urlpatterns = [
path('crud/', views.CrudView.as_view(), name='crud_ajax'),
]
Crud.html
{% extends 'base.html' %}
{% load static %}
{% block content %}
<div class="container">
<h1>Django Ajax CRUD</h1>
<div class="row">
<div class="col-md-4 ">
<h3>ADD USER</h3>
<form id="addUser" action="">
<div class="form-group">
<input class="form-control" type="text" name="name" placeholder="Name" required>
</div>
<div class="form-group">
<input class="form-control" type="text" name="address" placeholder="Address" required>
</div>
<div class="form-group">
<input class="form-control" type="number" name="age" min="10" max="100" placeholder="Age" required>
</div>
<button class="btn btn-primary form-control" type="submit">SUBMIT</button>
</form>
</div>
<div class="col-md-8">
<h3>USERS</h3>
<table id="userTable" class="table table-striped">
<tr>
<th>Name</th>
<th>Address</th>
2 of 9 3/22/20, 10:59 PM
Django Ajax CRUD - Execute CRUD Operations - Django https://studygyaan.com/django/how-to-execute-crud-using-django-ajax-and-json
<th colspan="3">Age</th>
</tr>
{% if users %}
{% for user in users %}
<tr id="user-{{user.id}}">
<td class="userName userData" name="name">{{user.name}}</td>
<td class="userAddress userData" name="address">{{user.address}}</td>
<td class="userAge userData" name="age">{{user.age}}</td>
<td align="center">
<button class="btn btn-success form-control" onClick="editUser({{user.id}})" data-toggle="modal" data-target="#myModal")">EDIT</button>
</td>
<td align="center">
<button class="btn btn-danger form-control" onClick="deleteUser({{user.id}})">DELETE</button>
</td>
</tr>
{% endfor %}
{% else %}
No Users
{% endif %}
</table>
</div>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Update User</h4>
</div>
<form id="updateUser" action="">
<div class="modal-body">
<input class="form-control" id="form-id" type="hidden" name="formId"/>
<label for="name">Name</label>
<input class="form-control" id="form-name" type="text" name="formName"/>
<label for="address">Address</label>
<input class="form-control" id="form-address" type="text" name="formAddress"/>
<label for="age">Age</label>
<input class="form-control" id="form-age" type="number" name="formAge" min=10 max=100/>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" >Save changes</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
{% endblock %}
{% block javascript %}
{% endblock javascript %}
In our HTML code, you will find the Add User form and modal for update user details, we will be going to use it later. So far our template should look like this:
3 of 9 3/22/20, 10:59 PM
Django Ajax CRUD - Execute CRUD Operations - Django https://studygyaan.com/django/how-to-execute-crud-using-django-ajax-and-json
We will not be using any forms.py instead, we have hardcoded HTML form directly in the template. As you can see in our crud.html file.
If you want Django to make your form then you can use crispy forms.
# Views.py
class CreateCrudUser(View):
def get(self, request):
name1 = request.GET.get('name', None)
address1 = request.GET.get('address', None)
age1 = request.GET.get('age', None)
obj = CrudUser.objects.create(
name = name1,
address = address1,
age = age1
)
user = {'id':obj.id,'name':obj.name,'address':obj.address,'age':obj.age}
data = {
'user': user
}
return JsonResponse(data)
Note– We are not rendering the template, we are just returning JsonResponse and we are also using Ajax Get Method.
We are getting the form data using request.GET.get(address, None), address is the form’s input name attribute. Then we are creating a user and sending back the user which we have created so to display it
on the web page.
# urls.py
from django.urls import path
from crud_ajax import views
urlpatterns = [
path('crud/', views.CrudView.as_view(), name='crud_ajax'),
path('ajax/crud/create/', views.CreateCrudUser.as_view(), name='crud_ajax_create'),
]
4 of 9 3/22/20, 10:59 PM
Django Ajax CRUD - Execute CRUD Operations - Django https://studygyaan.com/django/how-to-execute-crud-using-django-ajax-and-json
Now let again add javascript and jquery ajax request in Crud.html which we have created while listing the users
Crud.html
...
{% block javascript %}
<script>
// Create Django Ajax Call
$("form#addUser").submit(function() {
var nameInput = $('input[name="name"]').val().trim();
var addressInput = $('input[name="address"]').val().trim();
var ageInput = $('input[name="age"]').val().trim();
if (nameInput && addressInput && ageInput) {
// Create Ajax Call
$.ajax({
url: '{% url "crud_ajax_create" %}',
data: {
'name': nameInput,
'address': addressInput,
'age': ageInput
},
dataType: 'json',
success: function (data) {
if (data.user) {
appendToUsrTable(data.user);
}
}
});
} else {
alert("All fields must have a valid value.");
}
$('form#addUser').trigger("reset");
return false;
});
function appendToUsrTable(user) {
$("#userTable > tbody:last-child").append(`
<tr id="user-${user.id}">
<td class="userName" name="name">${user.name}</td>
'<td class="userAddress" name="address">${user.address}</td>
'<td class="userAge" name="age">${user.age}</td>
'<td align="center">
<button class="btn btn-success form-control" onClick="editUser(${user.id})" data-toggle="modal" data-target="#myModal")">EDIT</button>
</td>
<td align="center">
<button class="btn btn-danger form-control" onClick="deleteUser(${user.id})">DELETE</button>
</td>
</tr>
`);
}
</script>
{% endblock javascript %}
The working of the above JQuery is like that when you submit the form id=’addUser’, It will take the values of the input fields and ajax call will be gone to the server.
$.ajax({
url: '{% url "crud_ajax_create" %}',
data: {
'name': nameInput,
'address': addressInput,
5 of 9 3/22/20, 10:59 PM
Django Ajax CRUD - Execute CRUD Operations - Django https://studygyaan.com/django/how-to-execute-crud-using-django-ajax-and-json
'age': ageInput
},
dataType: 'json',
success: function (data) {
if (data.user) {
appendToUsrTable(data.user);
}
}
});
Let us understand what the above ajax request commanding to the browser.
url: '/ajax/crud/create/',
dataType: 'json',
data: {
'name': nameInput,
'address': addressInput,
'age': ageInput
},
Success Response – Once we receive response from ajax, execute the code:
When the user fills the form and submits it. Submitted data goes to the server and after validation into the database and the function appendToUsrTable is called. This appendToUsrTable function is just a
jQuery where it appends the user which we have added using User Add Form. When a user is added it will look like this:
class UpdateCrudUser(View):
def get(self, request):
id1 = request.GET.get('id', None)
name1 = request.GET.get('name', None)
address1 = request.GET.get('address', None)
age1 = request.GET.get('age', None)
obj = CrudUser.objects.get(id=id1)
obj.name = name1
obj.address = address1
obj.age = age1
obj.save()
user = {'id':obj.id,'name':obj.name,'address':obj.address,'age':obj.age}
6 of 9 3/22/20, 10:59 PM
Django Ajax CRUD - Execute CRUD Operations - Django https://studygyaan.com/django/how-to-execute-crud-using-django-ajax-and-json
data = {
'user': user
}
return JsonResponse(data)
# urls.py
urlpatterns = [
path('crud/', views.CrudView.as_view(), name='crud_ajax'),
path('ajax/crud/create/', views.CreateCrudUser.as_view(), name='crud_ajax_create'),
path('ajax/crud/update/', views.UpdateCrudUser.as_view(), name='crud_ajax_update'),
]
crud.html
...
// Create Django Ajax Call
$("form#updateUser").submit(function() {
var idInput = $('input[name="formId"]').val().trim();
var nameInput = $('input[name="formName"]').val().trim();
var addressInput = $('input[name="formAddress"]').val().trim();
var ageInput = $('input[name="formAge"]').val().trim();
if (nameInput && addressInput && ageInput) {
// Create Ajax Call
$.ajax({
url: '{% url "crud_ajax_update" %}',
data: {
'id': idInput,
'name': nameInput,
'address': addressInput,
'age': ageInput
},
dataType: 'json',
success: function (data) {
if (data.user) {
updateToUserTabel(data.user);
}
}
});
} else {
alert("All fields must have a valid value.");
}
$('form#updateUser').trigger("reset");
$('#myModal').modal('hide');
return false;
});
7 of 9 3/22/20, 10:59 PM
Django Ajax CRUD - Execute CRUD Operations - Django https://studygyaan.com/django/how-to-execute-crud-using-django-ajax-and-json
}
}
function updateToUserTabel(user){
$("#userTable #user-" + user.id).children(".userData").each(function() {
var attr = $(this).attr("name");
if (attr == "name") {
$(this).text(user.name);
} else if (attr == "address") {
$(this).text(user.address);
} else {
$(this).text(user.age);
}
});
}
Update user is similar to Create User. In views.py instead of create query, we are using an update query.
In Ajax Request call we are sending one more parameter id to identify the row in the database.
editUser – is used for updating the form id=”updateUser” which is inside the modal. And updateToUserTabel is used in the success of Ajax request for updating the user detail which we have updated.
class DeleteCrudUser(View):
def get(self, request):
id1 = request.GET.get('id', None)
CrudUser.objects.get(id=id1).delete()
data = {
'deleted': True
}
return JsonResponse(data)
# urls.py
urlpatterns = [
path('crud/', views.CrudView.as_view(), name='crud_ajax'),
path('ajax/crud/create/', views.CreateCrudUser.as_view(), name='crud_ajax_create'),
path('ajax/crud/update/', views.UpdateCrudUser.as_view(), name='crud_ajax_update'),
path('ajax/crud/delete/', views.DeleteCrudUser.as_view(), name='crud_ajax_delete'),
]
Crud.html
8 of 9 3/22/20, 10:59 PM
Django Ajax CRUD - Execute CRUD Operations - Django https://studygyaan.com/django/how-to-execute-crud-using-django-ajax-and-json
},
dataType: 'json',
success: function (data) {
if (data.deleted) {
$("#userTable #user-" + id).remove();
}
}
});
}
}
Deleting User using Ajax Django is one of the easiest ways. In ajax request, we are sending an id of the object which we want to delete to view. In View, delete query is executed and deleted flag is sent in
Response. In success, we directly write the jQuery function to remove the section which we want to remove from the table using id dynamically.
Conclusion
We are using Class-based views, which are simple and recommendable. We have used Jquery Ajax and JSON and Python. For CSS and styling, we have used Bootstrap. Python django crud tutorial . django
jquery ajax. crud operation in django example. django confirm delete template ajax.
9 of 9 3/22/20, 10:59 PM