How to enable 2FA in the Django admin

Now a days everyone has a smartphone, this type of 2FA setup is basically now free and accessible to everyone.  You can easily install a 2FA client app like Google Authenticator or Twilio Authy on your phone. Many websites also now support it and will probably become more and more common as it does improve security significantly.

On the server side, there are free and open source libraries you can use to implement these TOTP (time-based one-time password) systems.  So you no longer have to pay for these expensive servers and licenses.  It’s now completely accessible outside of the enterprise and you can implement it for free in your Django app.

In this post, I’ll quickly go over how you can secure your Django admin with TOTP 2FA using the django-otp package.

Step 1 : Install django-otp and qrcode for 2FA

The qrcode package is actually a optional One it is good include. it generates qrcode so that we can quickly scan with our phone to setup instead of manually typing things

pip install django-otp qrcode

Step 2 : Update your file

Add the following to your INSTALLED_APPS





Add the Following in bold in MIDDLEWARE after the AuthenticationMiddleware entry :


Now run

# migrate our app
python3 migrate

Creating a TOTP Device for 2FA

Now log into django admin to create an TOTP device. You can see it after logging in

login page

Click add and fill the details to create a new TOTP qrcode

add Device

 Now again go into totp device section and open the QRcode and scan it with your TOTP apps like Authy, Google Authenticator apps.

Scan the QR

Set Admin OTP Class –

Now go into django file in gfgblog, not in blog and add the lines

from django_otp.admin import OTPAdminSite = OTPAdminSite

Output –

Now logout and login into django admin you have enter OTP everytime you need to login into django admin.