Django form field and widget integration for Google reCAPTCHA services, supporting reCAPTCHA V2 and V3.
—
Django form field integration for adding reCAPTCHA validation to forms. The ReCaptchaField provides seamless integration with Django's form system, automatic validation with Google's API, and comprehensive error handling.
Main form field class that extends Django's CharField to provide reCAPTCHA validation. Always required and automatically validates user responses with Google's reCAPTCHA API during form validation.
class ReCaptchaField(forms.CharField):
"""
Django form field for reCAPTCHA validation.
Automatically validates reCAPTCHA responses with Google's API.
Always required - cannot be made optional.
"""
def __init__(self, public_key=None, private_key=None, *args, **kwargs):
"""
Initialize reCAPTCHA field.
Parameters:
- public_key (str, optional): Google reCAPTCHA public key.
Defaults to RECAPTCHA_PUBLIC_KEY setting or test key.
- private_key (str, optional): Google reCAPTCHA private key.
Defaults to RECAPTCHA_PRIVATE_KEY setting or test key.
- **kwargs: Standard Django CharField parameters
Note: Widget must be a subclass of ReCaptchaBase
"""
def validate(self, value):
"""
Validate reCAPTCHA response with Google API.
Parameters:
- value (str): reCAPTCHA response token from form submission
Raises:
- ValidationError: If reCAPTCHA validation fails
- HTTPError: If API communication fails
"""
def get_remote_ip(self):
"""
Extract client IP address from request context.
Returns:
str: Client IP address, checking X-Forwarded-For header first
"""The field automatically configures itself based on Django settings and provided parameters:
RECAPTCHA_PUBLIC_KEY and RECAPTCHA_PRIVATE_KEY settings by defaultdata-sitekey attribute on the widgetrequired=True (cannot be overridden)The field performs comprehensive validation during form processing:
The field provides specific error messages for different failure scenarios:
default_error_messages = {
"captcha_invalid": "Error verifying reCAPTCHA, please try again.",
"captcha_error": "Error verifying reCAPTCHA, please try again.",
}captcha_invalid: Validation failed (invalid response, low score, wrong action)captcha_error: API communication error (timeout, network issues)from django import forms
from django_recaptcha.fields import ReCaptchaField
class ContactForm(forms.Form):
name = forms.CharField(max_length=100)
email = forms.EmailField()
message = forms.CharField(widget=forms.Textarea)
captcha = ReCaptchaField()class SecureForm(forms.Form):
data = forms.CharField()
captcha = ReCaptchaField(
public_key="6Lc_custom_public_key",
private_key="6Lc_custom_private_key"
)from django_recaptcha.fields import ReCaptchaField
from django_recaptcha.widgets import ReCaptchaV2Invisible, ReCaptchaV3
class InvisibleForm(forms.Form):
data = forms.CharField()
captcha = ReCaptchaField(widget=ReCaptchaV2Invisible())
class V3Form(forms.Form):
data = forms.CharField()
captcha = ReCaptchaField(
widget=ReCaptchaV3(
action='submit_form',
required_score=0.5
)
)from django import forms
from django.contrib.auth.models import User
from django_recaptcha.fields import ReCaptchaField
class UserRegistrationForm(forms.ModelForm):
captcha = ReCaptchaField()
class Meta:
model = User
fields = ['username', 'email', 'password']Install with Tessl CLI
npx tessl i tessl/pypi-django-recaptcha