0
# Form Fields
1
2
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.
3
4
## Capabilities
5
6
### ReCaptchaField
7
8
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.
9
10
```python { .api }
11
class ReCaptchaField(forms.CharField):
12
"""
13
Django form field for reCAPTCHA validation.
14
15
Automatically validates reCAPTCHA responses with Google's API.
16
Always required - cannot be made optional.
17
"""
18
19
def __init__(self, public_key=None, private_key=None, *args, **kwargs):
20
"""
21
Initialize reCAPTCHA field.
22
23
Parameters:
24
- public_key (str, optional): Google reCAPTCHA public key.
25
Defaults to RECAPTCHA_PUBLIC_KEY setting or test key.
26
- private_key (str, optional): Google reCAPTCHA private key.
27
Defaults to RECAPTCHA_PRIVATE_KEY setting or test key.
28
- **kwargs: Standard Django CharField parameters
29
30
Note: Widget must be a subclass of ReCaptchaBase
31
"""
32
33
def validate(self, value):
34
"""
35
Validate reCAPTCHA response with Google API.
36
37
Parameters:
38
- value (str): reCAPTCHA response token from form submission
39
40
Raises:
41
- ValidationError: If reCAPTCHA validation fails
42
- HTTPError: If API communication fails
43
"""
44
45
def get_remote_ip(self):
46
"""
47
Extract client IP address from request context.
48
49
Returns:
50
str: Client IP address, checking X-Forwarded-For header first
51
"""
52
```
53
54
### Field Configuration
55
56
The field automatically configures itself based on Django settings and provided parameters:
57
58
- Uses `RECAPTCHA_PUBLIC_KEY` and `RECAPTCHA_PRIVATE_KEY` settings by default
59
- Falls back to Google's test keys for development
60
- Automatically sets `data-sitekey` attribute on the widget
61
- Always sets `required=True` (cannot be overridden)
62
63
### Validation Process
64
65
The field performs comprehensive validation during form processing:
66
67
1. **Basic Validation**: Calls parent CharField validation
68
2. **API Submission**: Submits response to Google's verification API
69
3. **Response Parsing**: Checks validation result and error codes
70
4. **V3 Action Validation**: For ReCaptchaV3 widgets, validates action matches
71
5. **Score Validation**: For V3 widgets with required_score, validates minimum score
72
73
### Error Handling
74
75
The field provides specific error messages for different failure scenarios:
76
77
```python { .api }
78
default_error_messages = {
79
"captcha_invalid": "Error verifying reCAPTCHA, please try again.",
80
"captcha_error": "Error verifying reCAPTCHA, please try again.",
81
}
82
```
83
84
- `captcha_invalid`: Validation failed (invalid response, low score, wrong action)
85
- `captcha_error`: API communication error (timeout, network issues)
86
87
## Usage Examples
88
89
### Basic Form Integration
90
91
```python
92
from django import forms
93
from django_recaptcha.fields import ReCaptchaField
94
95
class ContactForm(forms.Form):
96
name = forms.CharField(max_length=100)
97
email = forms.EmailField()
98
message = forms.CharField(widget=forms.Textarea)
99
captcha = ReCaptchaField()
100
```
101
102
### Custom Keys
103
104
```python
105
class SecureForm(forms.Form):
106
data = forms.CharField()
107
captcha = ReCaptchaField(
108
public_key="6Lc_custom_public_key",
109
private_key="6Lc_custom_private_key"
110
)
111
```
112
113
### Different Widget Types
114
115
```python
116
from django_recaptcha.fields import ReCaptchaField
117
from django_recaptcha.widgets import ReCaptchaV2Invisible, ReCaptchaV3
118
119
class InvisibleForm(forms.Form):
120
data = forms.CharField()
121
captcha = ReCaptchaField(widget=ReCaptchaV2Invisible())
122
123
class V3Form(forms.Form):
124
data = forms.CharField()
125
captcha = ReCaptchaField(
126
widget=ReCaptchaV3(
127
action='submit_form',
128
required_score=0.5
129
)
130
)
131
```
132
133
### ModelForm Integration
134
135
```python
136
from django import forms
137
from django.contrib.auth.models import User
138
from django_recaptcha.fields import ReCaptchaField
139
140
class UserRegistrationForm(forms.ModelForm):
141
captcha = ReCaptchaField()
142
143
class Meta:
144
model = User
145
fields = ['username', 'email', 'password']
146
```