icon picker
How to apply AJAX with Django 2.1

For many years, programmers tend to perform all the difficult and repetitive task that coding implies, until Frameworks appeared!
And thank God, Django is one of them.
Django is a high-level Python Web Framework, that ease rapid development rapid development, clean and pragmatic design. Even though, is python based which implies a faster learning curve, there are a lot of missing functionalities or pieces that as developers we need to find out, that how this tutorial came up!
Asynchronous Javascript and XML (AJAX ) in real life it’s such a beauty, it provides: data sending to web server in background, update content of a web page without refreshing, and finally read data from the web server after loaded. In simple words, access to dynamic content.
But, why does Django need this technologies? Does Django does not implement the AJAX functionalities? I’m sorry to answer this couple of questions but Django can not have everything that everyone wanted, even though, this framework has got an incredibly big community and a lot of resources, it needs help of others implementations to provide what every developer needs to fulfil their requirements, it’s like a big Lego puzzle, you can have a great structure but in order to do more, new pieces are needed.
Let’s begin by setting up a context, imagine that you’ve got an amazing app, with all beautiful styles, perfect UI and a well implemented Model View Controller (MVC) model, but wait…, your boss, stakeholder, client or even you notice something, is there a way to update content, save something or delete it without loading another page?
That happened to me, and probably in your working life you’ll face the same situation. So let me present you some good news, AJAX is the key to make any framework (Django) complete in Create-Read-Update-Delete(CRUD) functionalities, performance and responsivity. If you need to delete an entry of your model because of a mistake, or load a graph, update an existing object, even to handle different Application Programming Interfaces (API’s), AJAX is meant to solve that issue.
And of course, Django developers knew it, so they opened their arms to accept this union of technologies mentioned before.
As complicated or simple as it sounds, personally I couldn’t find a humble and fast tutorial to actually apply it on my projects, this is such a great issue nowadays. Imagine having all the information of the world in front of you but in a dead language or so bad written that no one could understand it, this really makes me nervous, so for avoiding this problem for future developers, people or humanity as well as making a good support for web beginners , here it is the basic and simplest AJAX-Django tutorial ever!
Firstly, we’re going to need to work in/with these different files:
javascript file
html file

To begin with we’re going to create a new url for the AJAX request, so open and let’s add:
from your_app.views import requestAjax
urlpatterns += [ path(‘my_ajax_request/’, requestAjax, name=’my_ajax_request’)]
The first line tells our Django project to import from “your_app” the view which will provide the server response to our AJAX call, meanwhile the second one, adds the url in the project as an accepted one in order to be capable of using that url for requests.
Now, the view is our next step, it’s necessary for any request that our app makes, so we need to have a controller that process this call being this the main purpose of having this function.
In add this line at the header:
from django.http import JsonResponse
Then create the following function:
def requestAjax(request): data = { ‘is_valid’: False } if request.is_ajax(): message = request.POST.get(‘message’) if message == ‘I want an AJAX response’: data.update(is_valid=True) data.update(‘response’=’This is the response you wanted’) return JsonResponse(data)
Right now, our server can be asked through the url my_ajax_request/ to provide a JsonResponse only if the AJAX call has a message that says ‘I want an AJAX response’. If this condition is fulfilled the server will answer a valid Json with a response: ‘This is the response you wanted’.
The purpose of making these extraction of the message inside the AJAX request is in order to explain that as well as you can get information, you can post it and save it. Hoping that this, can aid someone in need!
If you get through all of the above, I’m glad to tell you “ we’re almost done”.
Is time to work among the js file mentioned earlier, Django asks for protection versus Cross Site Request Forgery, so we need to get a cookie in order to generate a token, which would be linked to all our ajax request.
So please add this to your js file:
//Django basic setup for accepting ajax requests.// Cookie obtainer Django
function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue;}var csrftoken = getCookie('csrftoken');// Setup ajax connections safetly
function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));}$.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } }});
Now, the next code is going to be a function applicable to any button, window on load or modal, but there is a must: “unbind() and bind() the function to the item selected, or event.preventDefault(); it”
Time to append our code to the js:
//---------------------------------------------------------------//Our code! ->Made by us!$.ajax({url: '/my_ajax_request/',data: {'message': 'I want an AJAX response'},dataType: 'json',type: 'POST',success: function(data) {if (data.is_valid) {console.log(data.response);} else {console.log("You didn't message : I want an AJAX response");}}});
Finally, I’ll leave this up to you, create your own html file and decided whether a button, or on window load or by a timeout, the execution of the ajax function mentioned before.
Do not forget:
unbind() and bind() the function to the item selected, or event.preventDefault(); it
Link the javascript file to the html
Remember that the html needs to be loaded through a view of your app

Thanks for reading the tutorial, If you need some advice or any mistake please be free to comment it bellow. And remember dynamic content is great for most of the projects, and AJAX is at my consideration the best possible choose for it.
Django is love!
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
) instead.