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

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' 
EMAIL_HOST_USER = '<Gmail Id>' 

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

In 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 to send OTP to the received email id , also this function will send the generated otp as HttpResponse in front end.

So, the will look like this:

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")
     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 we will be defining path to call those functions from front end. For this we will write code in .

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

So, the will look like this:

from django.contrib import admin
from django.urls import path,include
from . import views
urlpatterns = [
     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:


<script src="" 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 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 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">

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:


     var otp_from_back="";
     function ajax_send_otp(){
        email = document.getElementById("email");
          function(data, status){
                  otp_from_back = data;
    function verify_otp(){
        var user_otp=document.getElementById("otp").value;
        if (user_otp==otp_from_back){
            document.getElementById("verify_text_div").innerHTML="OTP Verified";
            document.getElementById("verify_text_div").innerHTML="Try Again!!";

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 –

Clone the Repository

git clone

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 runserver

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