Learn how to Validate Username using Ajax in Django

What is Ajax?

Ajax Stands for Asynchronous JavaScript And XML. Ajax is not a programming language.

AJAX just uses a combination of:

  • A browser built-in XMLHttpRequest object (to request data from a web server)
  • JavaScript and HTML DOM (to display or use the data)

AJAX allows web pages to be updated asynchronously by exchanging data with a web server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.

Learn to create news app in django using web scapping technique

What we will be doing?

We will validate the username field in the RegistrationView, as soon as the user finishes typing the username(or focus is out of the username input field). We will do a simple check if the username is already taken or not.

For sake of simplicity, we will use class-based views

#your_app/views.py
from django.contrib.auth.forms import UserCreationForm 
from django.views.generic import CreateView  
class SignUpView(CreateView):     
   template_name = 'signup.html'     
   form_class = UserCreationForm

to configure urls.py

#urls.py
from django.urls import path
from your_app import views  
urlpatterns = 
[     
    path('register/', views.SignUpView.as_view(), name='signup'), 
]

signup.html

#signup.html
{% extends 'base.html' %}  
  {% block content %}   
    <form method="post">     
       {% csrf_token %}     
       {{ form.as_p }}     
       <button type="submit">Sign up</button>   
    </form> 
  {% endblock %}

Now we will work on Ajax Part, before that make sure you have imported jQuery in your project.

First, we gotta have a look at the HTML generated by the {{ form.as_p }}. We want to inspect the username field, which looks like that:

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

Open Javascript block in Signup.html

{% 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 %}

Make sure the event is firing correctly. In this case, as the name suggests, the change event will occur every time the value of the username field changes.

Now create a function in views.py to check if the username already exists or not

#views.py
from django.contrib.auth.models import User 
from django.http import JsonResponse
def check_username(request):
    username = request.GET.get(username)
    data = {
       'username_exists':      User.objects.filter(username__iexact=username).exists()
    }
    return JsonResponse(data)

Add a URL for this function

#urls.py
urlpatterns = [
       ......,
       path('check_username/', views.check_username, name='check_username),
]

Now create Ajax request in javascript block

Javascript Ajax

#signup.html
........
{% block javascript %}   
<script>     
   $("#id_username").change(function () {       
      var username = $(this).val();        
      $.ajax({        
            url: '/check_username/',         
            data: {           
                'username': username          
            },         
            dataType: 'json',            
            success: function (data) {           
                 if (data.username_exists) {             
                 alert("Username already taken");
                  
                 }         
            }       
      });      
   });   
</script> 
{% endblock %}
........

And that’s it you are good to

Feel free to ask for the full code in the comments

Cheers!!

Happy Coding!!

Stay Safe!!!

This Post Has 2 Comments

Leave a Reply