How to add a captcha in a Django website?

PythonServer Side ProgrammingProgramming

Captcha is one of the modern ways used for verification in websites; it is very cool way and every second website is using it. You can use Google captcha but it is really a headache to apply it; however in Django, we have a simpler method to do so.

In this article, we are going to learn how to create a captcha in a Django website. So, let's get started.

Example

First of all, create a Django project and an app.

Now install the django-simple-captcha library −

pip install django-simple-captcha

Go to settings.py and inside INSTALLED_APPS, add your app and "captcha": −

INSTALLED_APPS = [
   'django.contrib.admin',
   'django.contrib.auth',
   'django.contrib.contenttypes',
   'django.contrib.sessions',
   'django.contrib.messages',
   'django.contrib.staticfiles',
   "captchaproject", #My app name
   "captcha" # the module name
]

It will add captcha as an app.

In project's root directory, add the following lines −

from django.contrib import admin
from django.urls import path, include
urlpatterns = [
   path('admin/', admin.site.urls),
   path('', include("captchaproject.urls")),
   path('/captcha',include("captcha.urls"))
]

It will add url for my app and the captcha url where verification will occur.

In app's main directory, create a forms.py and type −

from django import forms
from captcha.fields import CaptchaField

class MyForm(forms.Form):
   captcha=CaptchaField()

Here we created a form with captcha field.

Don't forget to run "python manage.py migrate"

Now in app's view.py, add the following lines −

from django.shortcuts import render
from .forms import MyForm
# Create your views here.
def home(request):
   if request.method=="POST":
      form=MyForm(request.POST)
      if form.is_valid():
         print("success")
      else:
         print("fail")
   form=MyForm()
   return render(request,"home.html",{"form":form})

We render the form in home view and in POST handler, we verify the form or we can say captcha and after verification, we print the result.

Create an HTML file in the templates directory (directory where you add every HTML or CSS file that you render, I assume you know and already configure it) and add the following lines −

<!DOCTYPE html>
<html>
   <head>
      <title>Tut</title>
   </head>
   <body>
      <form method="POST" novalidate>
         {%csrf_token%}
         {{form.captcha}}
         <input type="submit" value="submit">
      </form>
   </body>
</html>

This is the frontend where we are rendering the captcha form.

We are done; now you can proceed to check the output.

Output

raja
Published on 26-Aug-2021 12:27:43
Advertisements