1000 Python Questions
Get 1 Python question daily. Join this telegram channel https://t.me/python1000questions
Advertise with us
ajax   3   8448
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 the signup form.


We will discuss the 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 the 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>
<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>
<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.
</div>


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


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


You can see an additional attribute data-url of the 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 the scope of this article and hence we are going with this easy method.



Javascript/AJAX Code:

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


On any text change in the input field, check_login the 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 the first time. But as soon as you enter something in the input field, one or the other div is displayed with a message based on the result received from ajax request.

Then we get the value of the 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 the input field.


In data, we are sending csrf_token and login/username. We defined the 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 an error message.



Django code to handle the Ajax request:

First, make sure you have a 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")
    else:   
        response_data = {}
        login = request.POST["login"]
        user = None
        try:
            try:
                user = UserModel.objects.get(login = login)
            except ObjectDoesNotExist as e:
                pass
            except Exception as e:
                raise e
            if not user:
                response_data["is_success"] = True
            else:
                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 the previous article, we developed a Hello World Django project. Here we have extended the same project and added the AJAX example in it. The code is available on Github.

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


Host Django App for Free


ajax   3   8448

3 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.

Paweł :
It's better to use Django Rest Framework.

Leave a comment:


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

SUBSCRIBE
Please subscribe to get the latest articles in your mailbox.

© 2017-2020 Python Circle   Contact   Sponsor   Archive   Sitemap