1000 Python Questions
Get 1 Python question daily. Join this telegram channel https://t.me/python1000questions
Advertise with us
ajax   2   5983
How to use AJAX with Django

AJAX is an acronym for Asynchronous JavaScript and XML. It is a group of inter-related technologies like JavaScript, DOM, XML, HTML, CSS etc. AJAX allows you to send and receive data asynchronously without reloading the web page.

At some point in your project development process you will need AJAX to execute some task. One fine example could be checking username availability on signup form.

We will discuss same scenario here and will guide you through the step by step process of using AJAX with Django.

How to use AJAX in Django:

So as per scenario discussed above, first we need to create a form with username field along with other fields. Use this code inside your form for login/username. 

<label for="login" class="col-md-2 control-label">Login</label>
<div class="col-md-4">
	<input type="text" class="form-control input-sm" name="login" id="login" placeholder="Login or Username" required="True" onkeyup="check_login(this);return false;" data-url="{% url "myapp_name:check_login" %}"/>
	{% csrf_token %}
<div class="col-md-6 col-sm-6" style="color:red;display:none;margin-top: 4px;"  id="login_not">
	<span class="glyphicon glyphicon-remove"></span> Username already taken.
<div class="col-md-6 col-sm-6" style="color: green;display: none;margin-top: 4px;" id="login_ok">
	<span class="glyphicon glyphicon-ok"></span> Username available.

We have created a input type of text which is a required field in form. On keyup event on this input field, we will call check_login function.

We are passing input field as parameter to this javascript function. So whenever text inside this input field changes, check_login function is triggered.

You can see an additional attribute data-url of input field. This is the URL where we send request from AJAX. We can hardcode this URL in javascript code but that won't be a good practice. Python/Django code should be limited to HTML only and should not be present in javascript.

We have also included csrf_token below the input field. CSRF token is required for all POST requests in Django. There are other ways to get the csrf token but that is out of scope of this article and hence we are going with this easy method.

Javascript/AJAX Code:

function check_login(element) {
	login = $(element).val();
	if (login == "") {
		url : $(element).attr("data-url"),
		data : {
			"csrfmiddlewaretoken" : $(element).siblings("input[name='csrfmiddlewaretoken']" ).val(),
		method: "POST",
		dataType : "json",
		success : function (returned_data) {			
			if (returned_data.is_success) {
			} else {

On any text change in input field, check_login method is triggered. Let see line by line, what is happening inside this function.

First we hide both the div where success/failure messages are being displayed. By default these divs are hidden when page is loaded first time. But as soon as you enter something in input field, one or the other div is displayed with message based on result received from ajax request.

Then we get the value of input field and if it is null/blank we do nothing and return from here. Then we make ajax call with parameters. URL is picked from data-url attribute of input field.

In data, we are sending csrf_token and login/username. We defined method as post and then defined actions to be taken on success or error response. If is_success variable in returned_data is set, then we show the div with success message else we show the div with error message.

Django code to handle the Ajax request:

First make sure you have URL (data-url in html code) in URL patterns.

In the view function check for availability of username and return appropriate JsonResponse.

def check_login(request):
    if request.method == "GET":
        raise Http404("URL doesn't exists")
        response_data = {}
        login = request.POST["login"]
        user = None
                user = UserModel.objects.get(login = login)
            except ObjectDoesNotExist as e:
            except Exception as e:
                raise e
            if not user:
                response_data["is_success"] = True
                response_data["is_success"] = False
        except Exception as e:
            response_data["is_success"] = False
            response_data["msg"] = "Some error occurred. Please let Admin know."

        return JsonResponse(response_data)

Import the required modules and models.

Code on Github:

In one of previous article we developed a Hello World Django project. Here we have extended the same project and added the AJAX example in it. Code is available on Github.

Github URL : https://github.com/anuragrana/ajax_in_django

Host Django App for Free

ajax   2   5983

2 thoughts on 'How To Use Ajax With Django'
Asif Khan :
I tried simlar AJAX code to update couple of fields in Django model from AJAX function. It works fine but when return from Django function as return jsonResponse(data) it show blank page with json response instead of my actual page. I think some library may be install to use AJAX with Django?
Admin :
Nothing needs to be installed. You need to populate HTML fields with the data received in JSON response.

Ronan Quennec :
Hi,In Django code, you indicate If not user: is_success = TrueIs there not an error ?Have a nice day.

Leave a comment:

*All Fields are mandatory. **Email Id will not be published publicly.

Please subscribe to get the latest articles in your mailbox.

© 2017-2020 Python Circle   Contact   Sponsor   Archive   Sitemap