CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-django-recaptcha

Django form field and widget integration for Google reCAPTCHA services, supporting reCAPTCHA V2 and V3.

Pending
Overview
Eval results
Files

form-fields.mddocs/

Form Fields

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.

Capabilities

ReCaptchaField

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
        """

Field Configuration

The field automatically configures itself based on Django settings and provided parameters:

  • Uses RECAPTCHA_PUBLIC_KEY and RECAPTCHA_PRIVATE_KEY settings by default
  • Falls back to Google's test keys for development
  • Automatically sets data-sitekey attribute on the widget
  • Always sets required=True (cannot be overridden)

Validation Process

The field performs comprehensive validation during form processing:

  1. Basic Validation: Calls parent CharField validation
  2. API Submission: Submits response to Google's verification API
  3. Response Parsing: Checks validation result and error codes
  4. V3 Action Validation: For ReCaptchaV3 widgets, validates action matches
  5. Score Validation: For V3 widgets with required_score, validates minimum score

Error Handling

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)

Usage Examples

Basic Form Integration

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()

Custom Keys

class SecureForm(forms.Form):
    data = forms.CharField()
    captcha = ReCaptchaField(
        public_key="6Lc_custom_public_key",
        private_key="6Lc_custom_private_key"
    )

Different Widget Types

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
        )
    )

ModelForm Integration

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

docs

client-api.md

configuration.md

form-fields.md

index.md

widgets.md

tile.json