OTP verification in Django: send, verify and handle every error
Written by Vivek SinghReviewed by the DiOTP team Published 3 December 2026Last updated 3 December 2026
10 min read
OTP verification in Django takes two views: one asks DiOTP to send a code and keeps the request_id in the session, the other sends that request_id with the typed code to DiOTP and logs the user in on a 200. DiOTP generates, stores and checks the code, so your database never holds it. This guide builds both views with plain HTTP calls through requests, maps every error code, handles the 429 limits including the 30 second resend cooldown, and tests the flow without sending an SMS.
How OTP verification works with DiOTP
DiOTP is an OTP API for India. Your server calls POST /v1/otp/send with the mobile number, DiOTP sends a code by SMS and replies with a request_id. When the user types the code, your server calls POST /v1/otp/verify with the request_id and the code. A 200 reply means the number is proven. Codes expire after 5 minutes and allow 5 attempts.
- The browser posts a phone number to your send view.
- The view validates the number, calls DiOTP and stores the request_id in request.session.
- The browser posts the typed code to your verify view.
- The view reads the request_id from the session, calls DiOTP and, on success, calls login().
The API key stays on the server, in an environment variable. Never put it in a template, a JavaScript bundle or a mobile app: anyone could read it and send codes on your account.
On DiOTP you can start without your own DLT registration: codes go out on DiOTP's registered header and pre-approved OTP template, which is what OTP without DLT means. If you only need the bare Python calls, the Python guide covers them with Flask. This page goes deeper into Django.
Build it step by step
- Sign up for DiOTP, create an API key in the dashboard and set it as DIOTP_API_KEY in your server's environment.
- Install requests with pip install requests, and create an app with python manage.py startapp otp.
- Add the client module that calls the API, and the error map.
- Add a form for the phone number and one for the code.
- Add the send and verify views, then wire them into urls.py.
- Run the tests, then try the flow on your own number in test mode.
settings.py
# settings.py
import os
# Fail at start-up, not on the first login, if the key is missing.
DIOTP_API_KEY = os.environ["DIOTP_API_KEY"]
# The default cache is per process. With several workers, share it so the
# per-IP limit counts across all of them.
CACHES = {
"default": {
"BACKEND": "django.core.cache.backends.redis.RedisCache",
"LOCATION": os.environ.get("REDIS_URL", "redis://127.0.0.1:6379/1"),
}
}
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_SECURE = True # HTTPS only in production
SESSION_COOKIE_SAMESITE = "Lax"Reading the key with os.environ["DIOTP_API_KEY"] makes Django refuse to start when it is missing, which is better than discovering it on a user's first login. Keep it in your host's secret settings or an untracked .env file loaded by your process manager.
A small DiOTP client with requests
Keep every call to DiOTP in one module. It adds the Bearer key, sets a 10 second timeout and turns any error reply into a DiotpError that carries the HTTP status and the stable error code. The request body uses digits only for to, the 10-digit number without +91, and country_code as the integer 91.
otp/diotp.py
# otp/diotp.py: a small client for the DiOTP API, using only requests.
import os
import time
import uuid
import requests
API = "https://api-diotp.diorbit.com/v1"
class DiotpError(Exception):
"""An error reply from DiOTP. Branch on .code, never on the message text."""
def __init__(self, status: int, code: str, message: str = ""):
super().__init__(f"{status} {code}: {message}")
self.status = status
self.code = code
self.message = message
def _post(path: str, body: dict, idempotency_key: str | None = None) -> dict:
headers = {
"Authorization": f"Bearer {os.environ['DIOTP_API_KEY']}",
"Content-Type": "application/json",
}
if idempotency_key:
headers["Idempotency-Key"] = idempotency_key
try:
res = requests.post(f"{API}{path}", json=body, headers=headers, timeout=10)
except requests.RequestException as exc:
raise DiotpError(0, "network_error", str(exc)) from exc
try:
data = res.json()
except ValueError:
data = {}
if res.status_code >= 400:
err = data.get("error") or {}
raise DiotpError(res.status_code, err.get("code", "unknown"), err.get("message", ""))
return data
def send_otp(phone: str, purpose: str = "login") -> dict:
"""Sends a code to a 10-digit Indian number. Returns request_id and expires_at."""
body = {"to": phone, "country_code": 91, "channel": "sms", "purpose": purpose}
key = str(uuid.uuid4()) # one key per user action, reused only for its retry
try:
return _post("/otp/send", body, key)
except DiotpError as exc:
# A timeout or a 503 is safe to retry once with the SAME key: DiOTP
# returns the first result instead of sending a second code.
if exc.code not in ("network_error", "sending_unavailable"):
raise
time.sleep(1.5)
return _post("/otp/send", body, key)
def verify_otp(request_id: str, code: str) -> dict:
"""Returns {"verified": True, ...} or raises DiotpError."""
return _post("/otp/verify", {"request_id": request_id, "code": code})Every send carries an Idempotency-Key. If the network drops or DiOTP answers 503 sending_unavailable, the client retries once with the same key, and DiOTP returns the first result instead of sending a second code. Never retry with a new key: that is a new send, and the user may get two codes. The field-by-field reference is on the send OTP docs page.
Validate input with Django forms
Clean the number before it reaches the API. People type spaces, dashes, a leading 0 or +91. The form strips all of that and accepts a 10-digit number starting with 6 to 9, which is the shape of an Indian mobile number. Rejecting bad input here saves an API call and gives the user a clearer message than 422 invalid_request would.
otp/forms.py
# otp/forms.py
import re
from django import forms
class PhoneForm(forms.Form):
phone = forms.CharField(max_length=20)
def clean_phone(self):
digits = re.sub(r"\D", "", self.cleaned_data["phone"])
if len(digits) == 12 and digits.startswith("91"):
digits = digits[2:]
if len(digits) == 11 and digits.startswith("0"):
digits = digits[1:]
if not re.fullmatch(r"[6-9]\d{9}", digits):
raise forms.ValidationError("Enter a 10-digit Indian mobile number.")
return digits
class CodeForm(forms.Form):
code = forms.RegexField(regex=r"^\d{4,10}$", error_messages={"invalid": "Enter the code from the SMS."})Map every error code to a reply
DiOTP returns errors as {"error":{"code":"...","message":"...","request_id":"..."}}. The code never changes, so branch on it; the message is for logs. Split the codes in two groups: ones the visitor can act on, and ones only you can fix.
otp/errors.py
# otp/errors.py: one place that decides what the visitor sees.
import logging
from .diotp import DiotpError
log = logging.getLogger(__name__)
# code -> (HTTP status for your client, message, seconds to wait or None)
USER_ERRORS = {
"resend_cooldown": (429, "Please wait 30 seconds before asking for another code.", 30),
"phone_hourly_limit": (429, "Too many codes for this number. Try again in an hour.", 3600),
"phone_daily_limit": (429, "Too many codes for this number today. Try again tomorrow.", None),
"api_key_minute_limit": (429, "We are busy right now. Please try again in a minute.", 60),
"rate_limited": (429, "We are busy right now. Please try again in a minute.", 60),
"invalid_code": (400, "That code is not right. Check the SMS and try again.", None),
"expired": (410, "This code has expired. Ask for a new one.", None),
"not_pending": (409, "This code is no longer valid. Ask for a new one.", None),
"not_found": (404, "We could not find that code. Ask for a new one.", None),
"too_many_attempts": (429, "Too many wrong tries. Ask for a new code.", None),
"invalid_request": (400, "Enter a valid 10-digit mobile number.", None),
}
def describe(exc: DiotpError) -> tuple[int, dict, int | None]:
known = USER_ERRORS.get(exc.code)
if known:
status, message, wait = known
return status, {"error": exc.code, "message": message}, wait
# unauthorized, trial_restricted, trial_used_up, insufficient_balance,
# account_suspended, channel_not_enabled, test_limit, sending_unavailable ...
# The visitor cannot fix these. Log the code and status, never the key.
log.error("DiOTP error status=%s code=%s", exc.status, exc.code)
return 503, {"error": "otp_unavailable", "message": "We could not send a code right now. Please try again shortly."}, None| Code | Status | Meaning | What to do |
|---|---|---|---|
| resend_cooldown | 429 | A code went to this number less than 30 seconds ago. | Keep the resend button disabled for 30 seconds. |
| phone_hourly_limit | 429 | 3 codes to this number in the last hour. | Ask the user to come back in an hour. |
| phone_daily_limit | 429 | 10 codes to this number today. | Ask the user to try tomorrow. |
| api_key_minute_limit, rate_limited | 429 | Your key or account is over its per-minute ceiling. | Show a short wait; alert yourself if it repeats. |
| invalid_code | 400 | The typed code is wrong. | Let the user try again, up to 5 attempts. |
| expired | 410 | The code is older than 5 minutes. | Offer a new code. |
| too_many_attempts | 429 | 5 wrong tries on this request. | Start over with a new code. |
| trial_restricted, trial_used_up, insufficient_balance | 403, 402 | Test mode or wallet problems. | Log and show a generic message. |
Every 429 from DiOTP means nothing was sent and nothing was charged. The full list, including unauthorized, account_suspended and channel_not_enabled, is on the error codes page.
The send and verify views
Two function views do the work. The request_id goes into request.session on send and is read back on verify, so the browser never holds it and nobody can verify a code against someone else's request.
otp/views.py
# otp/views.py
import time
from django.contrib.auth import get_user_model, login
from django.core.cache import cache
from django.http import JsonResponse
from django.views.decorators.http import require_POST
from .diotp import DiotpError, send_otp, verify_otp
from .errors import describe
from .forms import CodeForm, PhoneForm
PENDING = "otp_pending"
IP_LIMIT = 10 # send requests per IP ...
IP_WINDOW = 15 * 60 # ... in 15 minutes
def _client_ip(request):
# Use X-Forwarded-For only if YOUR proxy sets it; otherwise it can be faked.
return request.META.get("REMOTE_ADDR", "")
def _ip_allowed(request) -> bool:
key = f"otp-ip:{_client_ip(request)}"
cache.add(key, 0, IP_WINDOW)
try:
return cache.incr(key) <= IP_LIMIT
except ValueError: # the key expired between add and incr
cache.set(key, 1, IP_WINDOW)
return True
def _error(exc: DiotpError) -> JsonResponse:
status, body, wait = describe(exc)
if wait:
body["retry_after"] = wait
res = JsonResponse(body, status=status)
if wait:
res["Retry-After"] = str(wait)
return res
@require_POST
def send_code(request):
if not _ip_allowed(request):
return JsonResponse({"error": "too_many_requests", "message": "Too many requests. Try again later."}, status=429)
form = PhoneForm(request.POST)
if not form.is_valid():
return JsonResponse({"error": "invalid_phone", "message": form.errors["phone"][0]}, status=400)
phone = form.cleaned_data["phone"]
# Mirror DiOTP's 30 second cooldown locally: no API call, no wait for an error.
pending = request.session.get(PENDING)
if pending and pending["phone"] == phone and time.time() - pending["sent_at"] < 30:
wait = 30 - int(time.time() - pending["sent_at"])
res = JsonResponse({"error": "resend_cooldown", "message": "Please wait before asking again.", "retry_after": wait}, status=429)
res["Retry-After"] = str(wait)
return res
try:
data = send_otp(phone, purpose="login")
except DiotpError as exc:
return _error(exc)
request.session[PENDING] = {"request_id": data["request_id"], "phone": phone, "sent_at": time.time()}
return JsonResponse({"sent": True, "expires_at": data["expires_at"], "resend_in": 30})
@require_POST
def verify_code(request):
pending = request.session.get(PENDING)
if not pending:
return JsonResponse({"error": "no_pending_code", "message": "Ask for a code first."}, status=400)
form = CodeForm(request.POST)
if not form.is_valid():
return JsonResponse({"error": "invalid_code", "message": "Enter the code from the SMS."}, status=400)
try:
verify_otp(pending["request_id"], form.cleaned_data["code"])
except DiotpError as exc:
if exc.code != "already_verified": # a double tap: treat as success
if exc.code in ("expired", "not_pending", "too_many_attempts", "not_found"):
request.session.pop(PENDING, None) # this request is finished
return _error(exc)
request.session.pop(PENDING, None)
User = get_user_model()
user, _ = User.objects.get_or_create(username=f"+91{pending['phone']}")
# login() rotates the session key, which closes off session fixation.
login(request, user, backend="django.contrib.auth.backends.ModelBackend")
return JsonResponse({"verified": True})otp/urls.py
# otp/urls.py
from django.urls import path
from . import views
urlpatterns = [
path("otp/send/", views.send_code, name="otp-send"),
path("otp/verify/", views.verify_code, name="otp-verify"),
]
# project/urls.py
# path("api/", include("otp.urls")),A few details matter. The send view checks its own copy of the 30 second cooldown before calling DiOTP, so a fast double tap gets an instant 429 with a Retry-After header and no API call. DiOTP still enforces the real limit, so a second tab or device cannot get around it. On verify, already_verified is treated as success, because it almost always means the user pressed the button twice. When a request is finished (expired, not_pending or too_many_attempts), the view clears it from the session so the next attempt starts clean.
login() rotates the session key at the moment the user gains access, which closes off session fixation. The example creates users named by their phone number; swap that line for however your project finds or creates accounts. These are JSON views, so send the CSRF token from your page in the X-CSRFToken header, as Django's documentation describes for AJAX requests.
Rate limits: DiOTP's and your own
DiOTP limits every number to one code every 30 seconds, 3 an hour and 10 a day, and each API key to 30 sends a minute. Those protect each phone. They do not stop a script that sends to a different number each time, which is how SMS pumping drains a wallet. The per-IP counter in the send view adds that layer: ten send requests per IP in fifteen minutes. Tune it to your traffic, and put a bot check in front of public sign-up forms.
The counter uses Django's cache. The default local-memory cache is per process, so with several Gunicorn workers each one counts separately. Use a shared cache such as Redis in production, as in the settings above. Our guide to SMS pumping protection covers the wider defence.
On the client, read retry_after from any 429 reply and count down on the resend button. That turns the cooldown into something the user can see instead of an error.
Test without sending an SMS
Patch the two client functions in the views module and Django's test client can run the whole flow, including login, in milliseconds. The tests also pin down the behaviour that matters: a cooldown becomes a 429 with Retry-After, and account problems are hidden from the visitor.
otp/tests.py
# otp/tests.py
from unittest import mock
from django.test import TestCase, override_settings
from .diotp import DiotpError
@override_settings(CACHES={"default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}})
class OtpFlowTests(TestCase):
@mock.patch("otp.views.send_otp")
@mock.patch("otp.views.verify_otp")
def test_send_then_verify_logs_in(self, verify, send):
send.return_value = {"request_id": "req_1", "channel": "sms", "expires_at": "2026-12-03T10:05:00+00:00"}
verify.return_value = {"request_id": "req_1", "verified": True, "verified_at": "2026-12-03T10:01:00+00:00"}
res = self.client.post("/api/otp/send/", {"phone": "+91 98765 43210"})
self.assertEqual(res.status_code, 200)
send.assert_called_once_with("9876543210", purpose="login")
res = self.client.post("/api/otp/verify/", {"code": "482913"})
self.assertEqual(res.json(), {"verified": True})
verify.assert_called_once_with("req_1", "482913")
self.assertIn("_auth_user_id", self.client.session)
@mock.patch("otp.views.send_otp")
def test_cooldown_from_diotp_becomes_429_with_retry_after(self, send):
send.side_effect = DiotpError(429, "resend_cooldown", "wait")
res = self.client.post("/api/otp/send/", {"phone": "9876543210"})
self.assertEqual(res.status_code, 429)
self.assertEqual(res["Retry-After"], "30")
@mock.patch("otp.views.send_otp")
def test_account_errors_are_hidden(self, send):
send.side_effect = DiotpError(402, "insufficient_balance", "recharge")
res = self.client.post("/api/otp/send/", {"phone": "9876543210"})
self.assertEqual(res.json()["error"], "otp_unavailable")Then try it for real. A new DiOTP account has 10 free test messages, sent only to the mobile number you verified at sign-up. A send to any other number returns 403 trial_restricted, which is a good check that your error mapping works. Ask for a code twice within 30 seconds to see resend_cooldown, and wait more than 5 minutes before verifying to see expired. Recharge your wallet from ₹100 and the same key sends to any Indian mobile number.
