0
# Views and URLs
1
2
Django Simple Captcha provides dedicated view functions for serving captcha images, audio files, and AJAX refresh functionality. The URL configuration enables these views to be integrated into any Django application with proper routing.
3
4
## Capabilities
5
6
### Image Views
7
8
View functions for serving captcha images with support for different scaling factors and dynamic generation.
9
10
```python { .api }
11
def captcha_image(request, key, scale=1):
12
"""
13
Serve captcha image for given key with optional scaling.
14
15
Parameters:
16
- request: HttpRequest object
17
- key: str, captcha hashkey from URL
18
- scale: int, image scaling factor (1 or 2, default: 1)
19
20
Returns:
21
HttpResponse: PNG image with appropriate headers
22
23
Raises:
24
Http404: If captcha key not found or expired
25
"""
26
```
27
28
### Audio Views
29
30
View function for serving text-to-speech audio files for accessibility compliance.
31
32
```python { .api }
33
def captcha_audio(request, key):
34
"""
35
Serve captcha audio file for accessibility.
36
37
Parameters:
38
- request: HttpRequest object
39
- key: str, captcha hashkey from URL
40
41
Returns:
42
HttpResponse: WAV audio file with appropriate headers
43
44
Raises:
45
Http404: If captcha key not found, expired, or audio disabled
46
47
Requirements:
48
- Flite executable must be installed and configured
49
- CAPTCHA_FLITE_PATH setting must point to flite binary
50
"""
51
```
52
53
### AJAX Views
54
55
View function for refreshing captchas via AJAX without full page reload.
56
57
```python { .api }
58
def captcha_refresh(request):
59
"""
60
AJAX endpoint for refreshing captcha without page reload.
61
62
Parameters:
63
- request: HttpRequest object (typically AJAX POST)
64
65
Returns:
66
JsonResponse: New captcha data including key, image_url, audio_url
67
68
Response format:
69
{
70
'key': str, # New captcha hashkey
71
'image_url': str, # URL to new captcha image
72
'audio_url': str # URL to new captcha audio (None if audio disabled)
73
}
74
"""
75
```
76
77
### Image Generation Utilities
78
79
Internal utility functions used by the image view for creating captcha images.
80
81
```python { .api }
82
def getsize(font, text):
83
"""
84
Get text size for different PIL versions.
85
86
Parameters:
87
- font: PIL font object
88
- text: str, text to measure
89
90
Returns:
91
tuple: (width, height) of rendered text
92
"""
93
94
def makeimg(size):
95
"""
96
Create base image with configured background color.
97
98
Parameters:
99
- size: tuple, (width, height) for image
100
101
Returns:
102
PIL.Image: Base image with background color applied
103
"""
104
```
105
106
### URL Configuration
107
108
Pre-configured URL patterns for captcha functionality.
109
110
```python { .api }
111
# URL patterns defined in captcha.urls
112
urlpatterns = [
113
# Standard resolution captcha image
114
re_path(r'image/(?P<key>\w+)/$', captcha_image, {'scale': 1}, name='captcha-image'),
115
116
# High-resolution captcha image (2x scaling)
117
re_path(r'image/(?P<key>\w+)@2/$', captcha_image, {'scale': 2}, name='captcha-image-2x'),
118
119
# Captcha audio file
120
re_path(r'audio/(?P<key>\w+).wav$', captcha_audio, name='captcha-audio'),
121
122
# AJAX refresh endpoint
123
re_path(r'refresh/$', captcha_refresh, name='captcha-refresh'),
124
]
125
```
126
127
## Usage Examples
128
129
### Basic URL Integration
130
131
```python
132
# In your main urls.py
133
from django.urls import path, include
134
135
urlpatterns = [
136
# ... other patterns
137
path('captcha/', include('captcha.urls')),
138
]
139
```
140
141
### Custom View Integration
142
143
```python
144
from django.shortcuts import render
145
from captcha.models import CaptchaStore
146
from captcha.helpers import captcha_image_url, captcha_audio_url
147
148
def contact_view(request):
149
# Generate new captcha
150
captcha_key = CaptchaStore.generate_key()
151
152
context = {
153
'captcha_key': captcha_key,
154
'captcha_image': captcha_image_url(captcha_key),
155
'captcha_audio': captcha_audio_url(captcha_key),
156
}
157
return render(request, 'contact.html', context)
158
```
159
160
### AJAX Integration
161
162
```javascript
163
// Frontend JavaScript for captcha refresh
164
function refreshCaptcha() {
165
fetch('/captcha/refresh/', {
166
method: 'POST',
167
headers: {
168
'X-CSRFToken': getCookie('csrftoken'),
169
'Content-Type': 'application/json',
170
},
171
})
172
.then(response => response.json())
173
.then(data => {
174
// Update captcha image
175
document.getElementById('captcha-image').src = data.image_url;
176
177
// Update hidden key field
178
document.getElementById('id_captcha_0').value = data.key;
179
180
// Clear user input
181
document.getElementById('id_captcha_1').value = '';
182
183
// Update audio link if present
184
if (data.audio_url) {
185
document.getElementById('captcha-audio').href = data.audio_url;
186
}
187
});
188
}
189
```
190
191
### Template Usage
192
193
```html
194
<!-- In your Django template -->
195
<div class="captcha-container">
196
<img id="captcha-image" src="{% url 'captcha-image' captcha_key %}"
197
alt="Captcha Challenge">
198
199
<!-- Audio accessibility option -->
200
<a id="captcha-audio" href="{% url 'captcha-audio' captcha_key %}">
201
Listen to Audio Version
202
</a>
203
204
<!-- Refresh button -->
205
<button type="button" onclick="refreshCaptcha()">
206
Refresh Captcha
207
</button>
208
209
<!-- Hidden field for captcha key -->
210
<input type="hidden" name="captcha_0" value="{{ captcha_key }}">
211
212
<!-- User input field -->
213
<input type="text" name="captcha_1" placeholder="Enter captcha">
214
</div>
215
```
216
217
### High-Resolution Image Support
218
219
```html
220
<!-- Serve 2x resolution images for high-DPI displays -->
221
<img srcset="{% url 'captcha-image' captcha_key %} 1x,
222
{% url 'captcha-image-2x' captcha_key %} 2x"
223
src="{% url 'captcha-image' captcha_key %}"
224
alt="Captcha Challenge">
225
```
226
227
## Response Headers
228
229
The view functions set appropriate HTTP headers:
230
231
**Image Views:**
232
- `Content-Type: image/png`
233
- `Cache-Control: no-cache, no-store, must-revalidate`
234
- `Expires: 0`
235
236
**Audio Views:**
237
- `Content-Type: audio/wav`
238
- `Cache-Control: no-cache, no-store, must-revalidate`
239
- `Content-Disposition: attachment; filename="captcha.wav"`
240
241
**AJAX Views:**
242
- `Content-Type: application/json`
243
- `Cache-Control: no-cache`
244
245
## Error Handling
246
247
All views handle common error conditions:
248
249
- **404 Errors**: Invalid or expired captcha keys
250
- **410 Gone**: Explicitly expired captchas (for image/audio views)
251
- **Configuration Errors**: Missing flite binary for audio
252
- **Image Generation Errors**: Font or PIL configuration issues