Email OTP Verification Form using AJAX and Django Template

Django OTP Verification on Email and Phone – Two Factor Authentication in Django. In this tutorial, we will learn how to create a Registration Form for User Signup and simultaneously verifying email using AJAX. Without verifying the OTP user cannot fill up the form. You can also find this tutorial code on GitHub.

Django OTP Verification using Email

Let’s get started.

Django OTP Verification on Email and Phone

First we have to create a Django project. One can refer to the previous blogs to create project in Django.

In my case a have created a project named basic and an app named basicapp.

So the structure will be like this basic/basicapp

So, to include the SMTP in backend we have to write following code in your settings.py file.

settings.py

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' 
EMAIL_HOST_USER = '<Gmail Id>' 
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587 
EMAIL_USE_TLS = True 
EMAIL_HOST_PASSWORD = "<Password>"

Now the structure to send the mail is ready, you have to link it with the logic in views.py

In views.py we will be defining three functions:

home This function will render our home.html page that contains all the HTML and CSS part.

  1. generateOTP Which will generate 4 digit random OTP. For generating OTP we will be using some python libraries math and random .
  2. send_otp This function will call the code we have written in settings.py to send OTP to the received email id , also this function will send the generated otp as HttpResponse in front end.

So, the views.py will look like this:

views.py

from django.shortcuts import render
from django.http import HttpResponse
from django.core.mail import send_mail
import math, random

def home(request):
     return render(request, "home.html")

def generateOTP() :
     digits = "0123456789"
     OTP = ""
     for i in range(4) :
         OTP += digits[math.floor(random.random() * 10)]
     return OTP

def send_otp(request):
     email=request.GET.get   ("email")
     print(email)
     o=generateOTP()
     htmlgen = '<p>Your OTP is <strong>o</strong></p>'
     send_mail('OTP request',o,'<your gmail id>',[email], fail_silently=False, html_message=htmlgen)
     return HttpResponse(o)

Now after creating logic in views.py we will be defining path to call those functions from front end. For this we will write code in urls.py .

Here we will be defining two url patterns:

  1. For calling home.html as landing page of the website.
  2. For call the function send_otp in views.py

So, the urls.py will look like this:

urls.py

from django.contrib import admin
from django.urls import path,include
from . import views
urlpatterns = [
     path("",views.home,name="home"),
     path("send_otp",views.send_otp,name="send otp"),
]

After doing this backend part we will move toward our frontend.

For front end we will be creating a file home.html for writing HTML, CSS, JS, AJAX.

We will be writing html code for displaying fields for different inputs (such as email id, OTP, name, password) by the user.

So, in home.html the HTML, CSS will look like this:

home.html

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" type='text/javascript'></script>
<div id="email_div" style="display: block;" >

    <label for="email">Email</label>
    <input type="text" name="email" id="email">
    <button  onclick="ajax_send_otp()">Send OTP</button>
</div>
<div id="verify_text_div"></div>
<div id="otp_div" style="display: none;" >

    <label for="email">OTP</label>
    <input type="text" name="otp" id="otp">
    <button  onclick="verify_otp()">Verify</button>
</div>
<br>
<div id="form_div" style="display: none;" >
    <label for="username">Username</label>
    <input type="text" name="username" id="username">
    <label for="password">Password</label>
    <input type="password" name="password" id="password">
    <label for="con_password">Confirm Password</label>
    <input type="password" name="con_password" id="con_password">
    <input type="submit" value="Sign In">
</div>

This was all about the HTML and CSS part, now we will be writing some JavaScript and AJAX code in home.html . We will be defining a global variable say otp_from_back as an empty string.

Now we will create two functions:

  1. ajax_send_otp : This is the function which contains AJAX call and this function will firstly take the email entered by the user and send it to back end using AJAX. After successfully sending the email it will be saving the OTP in otp_from_back variable. Now, it will hide the field which was taking email and display another field to input the OTP by user.
  2. verify_otp : Once the OTP is entered by the user it will check it with the otp_from_back . If it matches, a message will be displayed as verified and the form will open automatically but if the OTP does not match a message will be displayed and user will try entering the OTP until it is verified.

So, the script part in home.html will look like this:

home.html

<script>
     var otp_from_back="";
     function ajax_send_otp(){
        document.getElementById("email_div").style.display='none';
        email = document.getElementById("email");
      $.post("/send_otp",
          {
              "email":email.value,
              "csrfmiddlewaretoken":"{{csrf_token}}"
          },
          function(data, status){
              if(status=="success"){
                  otp_from_back = data;
                  document.getElementById("otp_div").style.display='block';
                  }
     }
     );
     }
    function verify_otp(){
        var user_otp=document.getElementById("otp").value;
        if (user_otp==otp_from_back){
            document.getElementById("verify_text_div").style.color="green";            
            document.getElementById("verify_text_div").innerHTML="OTP Verified";
            document.getElementById("otp_div").style.display="none";
            document.getElementById("form_div").style.display="block";
        }
        else{
            document.getElementById("verify_text_div").style.color="red";
            document.getElementById("verify_text_div").innerHTML="Try Again!!";
        }
    } 
 </script>

And that’s all, our email verification will work now. Once the code is run output:

django otp
User entering OTP recieved on the mail
django otp
One can register once the OTP is verified

GitHub – Run Example Locally

Code available on GitHub – https://github.com/priyanshuarora1/Email-OTP-verification-form-using-AJAX-and-JS-in-Django

Clone the Repository

git clone https://github.com/priyanshuarora1/Email-OTP-verification-form-using-AJAX-and-JS-in-Django.git

Change Directory

cd Email-OTP-verification-form-using-AJAX-and-JS-in-Django

Create Virtual Environment – VirtualEnv

mkvirtualenv env

Run requirements file to install libraries using pip

pip install -r requirements.txt

Run the server

python3 manage.py runserver

And open http://localhost:8000/ in your browser.