See posts by tags

A Step-by-Step Guide to Integrating Google reCAPTCHA with django-recaptcha

  • 1 min read
  • 24 Feb, 2025

Introduction

Google reCAPTCHA is an essential tool to protect your website from spam and automated abuse. By verifying that users are human, it keeps your site secure and reliable. Using the django-recaptcha package, you can quickly integrate this feature into your Django project.

Prerequisites

  • A working Django project
  • Python installed on your system
  • Basic knowledge of pip and virtual environments

Step 1: Installation

Install the django-recaptcha package via pip:

pip install django-recaptcha

Add 'django_recaptcha' to your INSTALLED_APPS in settings.py:

INSTALLED_APPS = [
    # ... other apps,
    'django_recaptcha',
]

Step 2: Obtain Google reCAPTCHA Keys

  1. Visit the Google reCAPTCHA Admin Console and register your website.
  2. Choose the reCAPTCHA type (e.g., reCAPTCHA v2 "I'm not a robot" checkbox).
  3. After registration, you will receive a Site Key and a Secret Key.

Add these keys to your Django settings:

# settings.py
RECAPTCHA_PUBLIC_KEY = 'your-site-key'
RECAPTCHA_PRIVATE_KEY = 'your-secret-key'

Step 3: Integrate reCAPTCHA in Django Forms

Import the reCAPTCHA field and widget in your form:

from django import forms
from captcha.fields import ReCaptchaField
from captcha.widgets import ReCaptchaV2Invisible

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

Step 4: Update the Template

Render your form in the template and include the necessary JavaScript:

<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Submit</button>
</form>

Step 5: Testing and Final Steps

  1. Run your Django development server: python manage.py runserver
  2. Navigate to your form page to verify that the reCAPTCHA widget loads correctly.
  3. Submit the form to ensure proper validation.

Conclusion

By following these steps, you have successfully integrated Google reCAPTCHA into your Django project, adding a robust layer of security against bots and spam. Enjoy a safer, more secure web application!