Django reCAPTCHA

4.1.0 · active · verified Tue Apr 14

django-recaptcha is a Django application that integrates Google reCAPTCHA functionality into Django forms. It provides form fields and widgets for reCAPTCHA v2 (Checkbox, Invisible) and reCAPTCHA v3. The current version is 4.1.0, and the project is actively maintained with regular releases to support the latest Django and Python versions.

Warnings

Install

Imports

Quickstart

To quickly integrate django-recaptcha, first add `django_recaptcha` to your `INSTALLED_APPS` and configure your `RECAPTCHA_PUBLIC_KEY` and `RECAPTCHA_PRIVATE_KEY` in `settings.py`. Then, include `ReCaptchaField` in your Django form and render it in your template. For reCAPTCHA v3, you can use `ReCaptchaV3` widget and optionally define `RECAPTCHA_SCORE_THRESHOLD` in settings.

# settings.py
import os

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

RECAPTCHA_PUBLIC_KEY = os.environ.get('RECAPTCHA_PUBLIC_KEY', '')
RECAPTCHA_PRIVATE_KEY = os.environ.get('RECAPTCHA_PRIVATE_KEY', '')

# Optional: For reCAPTCHA v3, set a default score threshold
# RECAPTCHA_SCORE_THRESHOLD = 0.5

# forms.py
from django import forms
from django_recaptcha.fields import ReCaptchaField
from django_recaptcha.widgets import ReCaptchaV2Checkbox # or ReCaptchaV3

class ContactForm(forms.Form):
    name = forms.CharField(max_length=100)
    email = forms.EmailField()
    message = forms.CharField(widget=forms.Textarea)
    recaptcha = ReCaptchaField(widget=ReCaptchaV2Checkbox) # Default to V2 Checkbox

# views.py
from django.shortcuts import render, redirect
from .forms import ContactForm

def contact_view(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            # Process the form data
            # For ReCaptchaV3, you might check form.cleaned_data['recaptcha'].get('score')
            return redirect('success_url') # Replace with your success URL name
    else:
        form = ContactForm()
    return render(request, 'contact.html', {'form': form})

# templates/contact.html
<!-- Make sure to load the Google reCAPTCHA API script in your base template or head, e.g., -->
<!-- <script src="https://www.google.com/recaptcha/api.js" async defer></script> -->

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

view raw JSON →