Django OTP
django-otp is a pluggable framework designed to integrate two-factor authentication (2FA) into Django projects using one-time passwords (OTPs). It provides the core framework and common OTP algorithms (HOTP, TOTP), allowing developers to build custom 2FA solutions or leverage existing plugins. The current version is 1.7.0, and the project maintains a healthy release cadence with active maintenance.
Warnings
- breaking Older versions of django-otp have dropped support for legacy Python and Django versions. For instance, v0.3.11 dropped Python 2.6 and Django 1.4. The current version (1.7.0) explicitly requires Python >=3.8. Ensure your environment meets the `requires_python` specification.
- gotcha Failing to add `django_otp.middleware.OTPMiddleware` to your `MIDDLEWARE` setting or placing it incorrectly (it should typically come after `AuthenticationMiddleware`) will prevent OTP verification from functioning correctly.
- gotcha `django-otp` is a low-level framework for managing OTPs, not a complete, opinionated two-factor authentication application. While it provides the building blocks, you will need to implement views, forms, and user flows or use a higher-level library like `django-two-factor-auth` for a ready-to-use solution.
- gotcha To enable QR code generation for HOTP/TOTP devices in the Django admin interface, you must explicitly install either the `qrcode` or `segno` Python package. Without one of these, QR codes will not be displayed.
Install
-
pip install django-otp
Imports
- Device
from django_otp.models import Device
- TOTPDevice
from django_otp.plugins.otp_totp.models import TOTPDevice
- devices_for_user
from django_otp import devices_for_user
- otp_required
from django_otp.decorators import otp_required
- OTPMiddleware
from django_otp.middleware import OTPMiddleware
Quickstart
# settings.py
INSTALLED_APPS = [
# ... other Django apps
'django_otp',
'django_otp.plugins.otp_totp', # Example: Time-based One-Time Passwords
# 'django_otp.plugins.otp_hotp', # Example: HMAC-based One-Time Passwords
# ... other OTP plugins (e.g., django-otp-sms)
]
MIDDLEWARE = [
# ... other Django middleware
'django_otp.middleware.OTPMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware', # Ensure this is before OTPMiddleware
# ...
]
# urls.py (example for admin integration)
from django.contrib import admin
from django.urls import path
from django_otp.admin import OTPAdminSite
admin.site.__class__ = OTPAdminSite
urlpatterns = [
path('admin/', admin.site.urls),
]
# After configuring, run migrations:
# python manage.py migrate