Ever wondered how to add a captcha field in your Django forms? I’ll show you how to do this! Captchas are a great way to secure your site from spamming, or bot attacks. So, adding a captcha field to your authentication forms are a great way to enhance your site’s UX. Let’s get started.
Make a Captcha Field in Django
Project Setup
For this, you need to install a package called django-simple-captcha
. This enables us to easily us captcha field in our Django forms just like other fields.
pip install django-simple-captcha
Now, create a django project and a django app:
django-admin startproject django_captcha cd django_captcha django-admin startapp app
Modifying settings.py
Add ‘app
‘ (Your app name) and 'captcha
‘ (app provided by django-simple-captcha) in your INSTALLED_APPS
of settings.py:
.... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app', 'captcha'] ....
Configuring root urls
Modify the django_captcha/urls.py as below:
from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('app.urls')), path('captcha/', include('captcha.urls')) ]
We’re routing the empty path to our app. And we’re making our project accessible to captcha package by adding ‘captcha’ in our root urls.
I’ll be making a templates folder in our app itself, so I won’t bother about tweaking the settings.py for template lookup.
Configuring app/urls
Add the following lines to app/urls.py:
from django.urls import path from . import views urlpatterns = [ path('', views.home, name="home") ]
Creating a captcha in forms.py
Now, I’ll create a django form in app/forms.py (Make a file called forms.py in your app folder). Add the following lines to it:
from django import forms from captcha.fields import CaptchaField class MyForm(forms.Form): # You can add other form fields here! captcha = CaptchaField()
For the sake of simplicity, I’m adding only the captcha field, but feel free to add whatever you want.
Making our views
I’ll use the django messages framework displaying success and failure of the captcha (This is optional, can do this without this). Make sure your app/views.py looks like this:
from .forms import MyForm from django.shortcuts import render from django.contrib import messages def home(request): if request.method == "POST": form = MyForm(request.POST) if form.is_valid(): messages.success(request, 'Success!') else: messages.error(request, 'Wrong Captcha!') form = MyForm() return render(request, 'home.html', {'form': form})
As you can see, I’m just doing basic form manipulation in my views (a captcha field is just a form field right?). Now, finally we need to make our template called ‘home.html‘. Make a file called ‘home.html’ in app/templates/home.html (Yeah, create a folder with name templates too).
Making our template
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Captcha</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous"> </head> <body> <h3 class="text-center mt-3 text-info">Django Captcha</h3> {% if messages %} {% for message in messages %} <div class="alert text-center mt-5 alert-{{message.tags}}"> {{message}} </div> {% endfor %} {% endif %} <form action="" method="post" class="text-center mt-5" novalidate> {% csrf_token %} {{form.captcha}} <input type="submit" class="btn btn-primary" value="Submit"> </form> </body> </html>
I’m using bootstrap in my template. Just place bootstrap cdn in your <head> … </head> for your template.
Yeah, we’re done with this. Finally you just need to do these steps,
python manag.py makemigrations python manage.py migrate
Now, start your development server with python manage.py runserver
and open 127.0.0.1:8000 in your favourite browser. That’s it!
Check out my code at GitHub https://github.com/Chandu-4444/django-captcha