Django 2 Ajax CRUD with Python 3.7 and jQuery

Django 2 Ajax CRUD with Python 3.7 and jQuery

In this post we will give you information about Django 2 Ajax CRUD with Python 3.7 and jQuery. Hear we will give you detail about Django 2 Ajax CRUD with Python 3.7 and jQueryAnd how to use it also give you demo for it if it is necessary.

In this tutorial, you’ll learn how to send Ajax requests in Django 2 and Python 3.7 to add CRUD operations in your application and manipulate your Django models and database without having to refresh your web pages each time.

Ajax stands for Asynchronous JavaScript and XML and it’s a way for getting data from the server and updating the page on the fly without refreshing the page.

Creating a Virtual Environment

Make sure you have Python 3 installed (Python 3.7 is the latest as of this writing) and start by creating a virtual environment for your project’s packages:

$ python -m venv myenv

Next, activate your virtual environment using:

$ source myenv/bin/activate

Installing Django 2 and Creating a Project

Now, you need to install Django using pip:

$ python -m pip install django

Next, create a Django project using:

$ django-admin startproject djangoajaxdemo

Next you need to create a Django application using the script:

$ cd djangoajaxdemo$ python startapp rooms

Next you need to add it to your project’s installed apps array in the file:


Adding jQuery

In this tutorial, we’ll be using jQuery to send Ajax requests to Django. You can also use any other HTTP client like Axios, the JavaScript Fetch API available on modern browsers or the XMLHttpRequest interface.

First of all, you need to get jquery from the official website and include it in your project or use a CDN. Go to the official website and get the CDN of the version of jQuery you want to use.

In my case, I’ll be using jQuery 3.3.1 from

Inside the rooms application, create a templates/rooms folder and create a base.html file:

{% load static %}<!DOCTYPE html><htmllang="en"><head><metacharset="utf-8"><metahttp-equiv="X-UA-Compatible"content="IE=edge"><metaname="viewport"content="width=device-width, initial-scale=1"><title> Django Ajax CRUD with jQuery</title><linkrel="stylesheet"href=""crossorigin="anonymous"></head><body><divclass="container d-flex h-100"><divclass="row justify-content-center"><divclass="col-10">          {% block main %}          {% endblock %}        </div></div></div>{% block js %}<script src=""></script>{% endblock %}{% block extrajs %}{% endblock %}  </body></html>

Adding a Model

We’ll be adding CRUD operations against a Room model. Open the rooms/ file and add the following code:


Adding CRUD Views

In the rooms/ file add the following class based and generic views for performing CRUD operations:

fromdjango.views.genericimportViewfromdjango.httpimportJsonResponsefromdjangoimportformsfromdjango.views.decorators.csrfimportcsrf_exemptfromdjango.utils.decoratorsimportmethod_decoratorfromdjango.forms.modelsimportmodel_to_dictfrom.modelsimportRoomclassRoomForm(forms.ModelForm):classMeta:model=Roomfields='__all__'classRoomList(View):defget(self,request):rooms=list(Room.objects.all().values())data=dict()data['rooms']=roomsreturnJsonResponse(data)classRoomDetail(View):defget(self,request,pk):room=get_object_or_404(Room,pk=pk)data=dict()data['room']=model_to_dict(room)returnJsonResponse(data)@method_decorator(csrf_exempt,name='dispatch')classRoomCreate(CreateView):defpost(self,request):data=dict()form=RoomForm(request.POST)ifform.is_valid()['room']=model_to_dict(room)else:data['error']="form not valid!"returnJsonResponse(data)classRoomUpdate(View):defpost(self,request,pk):data=dict()room=Room.objects.get(pk=pk)form=RoomForm(instance=room,data=request.POST)ifform.is_valid()['room']=model_to_dict(room)else:data['error']="form not valid!"returnJsonResponse(data)classRoomDelete(View):defpost(self,request,pk):data=dict()room=Room.objects.get(pk=pk)ifroom:room.delete()data['message']="Room deleted!"else:data['message']="Error!"returnJsonResponse(data)

Next, let’s add the urls. Open the file and add:


Adding a Template

Since we’ll be using Ajax for making CRUD operations in our Django application we will not need multiple pages or templates but instead we’ll conceive our application as a Single Page Application.

Let’s create a main.html file inside the rooms/templates/rooms folder with the following content:

{% extends 'rooms/base.html' %}{% block main %}  {% endblock %}{% block extrajs %}<script  src="{% static 'js/app.js' %}"></script>{% endblock %}

Next under your project’s root folder create the static/js/ folder and add an app.js file with the following content:


In your file, add the following url pattern so you can access your static files in development mode:

fromdjango.confimportsettings# [...]ifsettings.DEBUG:fromdjango.contrib.staticfiles.urlsimportstaticfiles_urlpatternsurlpatterns+=staticfiles_urlpatterns()

In the file, add the following setting to configure your static folder:


If your run your application and visit the you should see a Hello! in the console of your browser which means you static files are configured correctly.

In this tutorial, we’ll implement the list and delete operations. For create and update operations we’ll see them in the next tutorial.

Getting Rooms with jQuery.ajax()

In your app.js file, add the following code to get data from the rooms/list endpoint by sending a GET Ajax request:

$.ajax({url:'/rooms/list',type:'get',dataType:'json',success:function(data){letrows='';data.rooms.forEach(room=>{rows+='<tr><td>${room.room_number}</td><td>${}</td><td>${room.nobeds}</td><td>${room.room_type}</td><td><buttonclass="btn deleteBtn"data-id="${}">Delete</button><buttonclass="btn updateBtn"data-id="${}">Update</button></td></tr>';});$('[#myTable]( > tbody').append(rows);$('.deleteBtn').each((i,elm)=>{$(elm).on("click",(e)=>{deleteRoom($(elm))})})}});

Deleting Rooms with jQuery.ajax()

Next, you need to add an implementation for the deleteRoom(e) method:


Now go back to your rooms/templates/rooms/main.html template and add the table:

{% block main %}<tableclass="table table-bordered"id="myTable"><thead><th>Room Number</th><th>Name</th><th>Number of Beds</th><th>Type</th><th>Actions</th></thead><tbody></tbody></table><divid="roomform"><buttonid="createRoom"class="btn"> Create Room </button></div>{% endblock %}

This is a screenshot of our page at this point:

Django Ajax and jQuery

In the next tutorial, we’ll see how to create a form and send it with jQuery and Ajax to our Django endpoints to create and update rooms.

Hope this code and post will helped you for implement Django 2 Ajax CRUD with Python 3.7 and jQuery. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US