Django AJAX and RSS – Free Django Tutorials

So in this post we will see how django works with AJAX requests and RSS.

How to Work With AJAX Request In Django

In your web application,you may face a situation many times where you want to use AJAX requests.AJAX requests is a great resource that will enable the web applications to be faster and more dynamic.We will use jQuery to east the implementation part in this post.You can use any different framework of your choice.

Initial Setup

Our base.html file will look as following:

{% load static %}<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>{% block title %}Default Title{% endblock %}</title>
    <link rel="stylesheet" type="text/css" href="{% static 'css/app.css' %}">
    {% block stylesheet %}{% endblock %}
  </head>
  <body>
    <header>
      ...
    </header>
    <main>
      {% block content %}
      {% endblock %}
    </main>
    <footer>
      ...
    </footer>
    <script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
    <script src="{% static 'js/app.js' %}"></script>
    {% block javascript %}{% endblock %}
  </body>
</html>

We will add all the jQuery and  all the JavaScript resources at the end of HTML page for two reasons:
1. To guarantee that DOM will be loaded only when the script is executed.
2.To avois the inline scripts.

All the extra javascript related to our project will goes inside the {% block javascript %}{% endblock %} block.

Sample Scenario

Suppose for a example we want to validate the username field in a sign up views,whenevar user finish typing the desired username.At the time of validation you want to check that if the username is already taken or not.

Change the views.py file as following:

from django.contrib.auth.forms import UserCreationForm
from django.views.generic.edit import CreateView

class SignUpView(CreateView):
    template_name = 'core/signup.html'
    form_class = UserCreationForm

Change the urls.py file as following:

from django.conf.urls import url
from core import views

urlpatterns = [
    url(r'^signup/$', views.SignUpView.as_view(), name='signup'),
]

change the signup.html file as following:

{% extends 'base.html' %}

{% block content %}
  <form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Sign up</button>
  </form>
{% endblock %}

Ajax Request

Now to validate if the username is already taken or not,let’s implement an asynchronous request.So first we have to inspect the username field as following:

First we will inspect the username field which will looks like this:

<input type="text" required="" name="username" maxlength="150" id="id_username" autofocus="">

To reference to the username field,all we need is it’s ID,which is id_username.We can create a listener for the username’s field change event:

Now change the singup.html file as following:

{% extends 'base.html' %}

{% block javascript %}
  <script>
    $("#id_username").change(function () {
      console.log( $(this).val() );
    });
  </script>
{% endblock %}

{% block content %}
  <form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Sign up</button>
  </form>
{% endblock %}

You can check before going forward that weather this listener is working correctly or not.In the above case change event will occur every time when the value of the username field changes.

Now for just checking we will create view that checks if a given username taken by user is already present or not and will return that response as a JSON.

Now Change the views.py file as following:

from django.contrib.auth.models import User
from django.http import JsonResponse

def validate_username(request):
    username = request.GET.get('username', None)
    data = {
        'is_taken': User.objects.filter(username__iexact=username).exists()
    }
    return JsonResponse(data)

change the urls.py file as following:

from django.conf.urls import url
from core import views

urlpatterns = [
    url(r'^signup/$', views.SignUpView.as_view(), name='signup'),
    url(r'^ajax/validate_username/$', views.validate_username, name='validate_username'),
]

and change the signup.html template as following:

{% extends 'base.html' %}

{% block javascript %}
  <script>
    $("#id_username").change(function () {
      var username = $(this).val();

      $.ajax({
        url: '/ajax/validate_username/',
        data: {
          'username': username
        },
        dataType: 'json',
        success: function (data) {
          if (data.is_taken) {
            alert("A user with this username already exists.");
          }
        }
      });

    });
  </script>
{% endblock %}

{% block content %}
  <form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Sign up</button>
  </form>
{% endblock %}

This is all about AJAX requests in django.

Leave a Comment

Your email address will not be published. Required fields are marked *