how to ajax   0   26
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>
<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 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_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 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")
    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 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


Please comment in case of any issue.


how to ajax   0   26

0 thoughts on 'How To Use Ajax With Django'
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.



Recent Posts: