Implement Captcha in Django 

When I first started integrating Google reCAPTCHA into Django forms, I realized how essential it is to protect web applications from spam, bots, and automated attacks. Over the years, I’ve seen many projects suffer from fake submissions and malicious traffic, especially in forms like contact pages, user registrations, and feedback forms.

Google reCAPTCHA is a reliable and widely used tool to prevent these issues. In this guide, I’ll walk you through how to add Google reCAPTCHA to your Django forms with clear, practical examples.

Let’s start!

What is Google reCAPTCHA and Why Use It?

Google reCAPTCHA is a free service that helps protect your website from spam and abuse by verifying that a user is a human, not a robot. It comes in several versions:

  • reCAPTCHA v2: The classic “I’m not a robot” checkbox.
  • reCAPTCHA v3: A behind-the-scenes score-based system that doesn’t interrupt users.
  • Invisible reCAPTCHA: Runs in the background and only challenges suspicious traffic.

For most Django forms, reCAPTCHA v2 is the easiest to implement and provides a good balance of security and user experience.

Check out If Condition In Django Template

Prerequisites

  • Python 3.x installed
  • Django project set up (I’ll assume Django 3.x or newer)
  • Google reCAPTCHA site key and secret key (from Google reCAPTCHA Admin Console)

Step 1: Register Your Site with Google reCAPTCHA

Head over to the Google reCAPTCHA Admin Console and register your website.

  • Choose reCAPTCHA v2 (“I’m not a robot” Checkbox).
  • Add your domain (e.g., yourdomain.com).
  • Accept terms and submit.
  • You’ll get two keys: Site Key and Secret Key. Keep these handy.

Step 2: Install Required Python Package

To simplify integration, I recommend using the django-recaptcha package. It wraps the reCAPTCHA widget and validation nicely.

pip install django-recaptcha

Step 3: Configure Django Settings

Add captcha to your INSTALLED_APPS in settings.py:

INSTALLED_APPS = [
    # other apps
    'captcha',
]

Add your Google reCAPTCHA keys to settings.py:

RECAPTCHA_PUBLIC_KEY = 'your-site-key-here'
RECAPTCHA_PRIVATE_KEY = 'your-secret-key-here'

For example:

RECAPTCHA_PUBLIC_KEY = '6Lc_aX0UAAAAABxY8xXxXxXxXxXxXxXxXxXxXx'
RECAPTCHA_PRIVATE_KEY = '6Lc_aX0UAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe'

Read Pyramid vs. Django

Step 4: Create a Django Form with reCAPTCHA

Here’s a simple contact form example that includes reCAPTCHA:

# forms.py
from django import forms
from captcha.fields import ReCaptchaField
from captcha.widgets import ReCaptchaV2Checkbox

class ContactForm(forms.Form):
    name = forms.CharField(max_length=100)
    email = forms.EmailField()
    message = forms.CharField(widget=forms.Textarea)
    captcha = ReCaptchaField(widget=ReCaptchaV2Checkbox())

Step 5: Create a View to Handle the Form

In your views.py, handle the form submission and validation:

# views.py
from django.shortcuts import render
from .forms import ContactForm
from django.http import HttpResponseRedirect
from django.urls import reverse

def contact_view(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            # Process form data here (e.g., send email)
            # For example:
            name = form.cleaned_data['name']
            email = form.cleaned_data['email']
            message = form.cleaned_data['message']
            # Send email or save to DB
            return HttpResponseRedirect(reverse('contact-success'))
    else:
        form = ContactForm()
    return render(request, 'contact.html', {'form': form})

Step 6: Create Templates

Create a simple template contact.html:

<!-- templates/contact.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Contact Us</title>
    {% csrf_token %}
    {{ form.media }}
</head>
<body>
    <h1>Contact Us</h1>
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Send</button>
    </form>
</body>
</html>

Make sure you load the form media to render the reCAPTCHA widget properly.

Check out Print Django Environment Variables

Step 7: Add URL Patterns

Add the URL for your contact page in urls.py:

# urls.py
from django.urls import path
from .views import contact_view

urlpatterns = [
    path('contact/', contact_view, name='contact'),
    path('contact/success/', lambda request: render(request, 'success.html'), name='contact-success'),
]

Create a simple success.html:

<!-- templates/success.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Success</title>
</head>
<body>
    <h1>Thank you for contacting us!</h1>
    <p>We will get back to you shortly.</p>
</body>
</html>

You can refer to the screenshot below to see the output.

django reCAPTCHA

Read Google Authentication in Django

Alternative Method: Manual Integration Without django-recaptcha

If you prefer not to use a third-party package, you can manually add reCAPTCHA by:

  1. Adding the reCAPTCHA widget script in your form template.
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
  1. Adding the widget in your form:
<div class="g-recaptcha" data-sitekey="your-site-key"></div>
  1. In your Django view, after form submission, verify the token by sending a POST request to Google’s API:
import requests

def contact_view(request):
    if request.method == 'POST':
        recaptcha_response = request.POST.get('g-recaptcha-response')
        data = {
            'secret': 'your-secret-key',
            'response': recaptcha_response
        }
        r = requests.post('https://www.google.com/recaptcha/api/siteverify', data=data)
        result = r.json()
        if result.get('success'):
            # Process form data
            pass
        else:
            # Return error message
            pass
    # rest of the view

This method gives you full control but requires more code and maintenance.

Adding Google reCAPTCHA to your Django forms is a simple way to secure your application from spam and bots. The django-recaptcha package simplifies this process, letting you focus on your app’s core logic rather than worrying about security details.

If you want to keep your forms user-friendly while adding a solid security layer, this approach works great for any US-based business website, whether it’s a contact form, registration page, or feedback form.

You may also like to read Django-related posts:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.