0
# Django Simple Captcha
1
2
A comprehensive Django captcha system that enables developers to add CAPTCHA image challenges to any Django form for enhanced security and spam prevention. Provides extensive customization options including custom challenge types, configurable image generation with noise and filter functions, text-to-speech audio output for accessibility compliance, and Ajax refresh capabilities.
3
4
## Package Information
5
6
- **Package Name**: django-simple-captcha
7
- **Language**: Python
8
- **Framework**: Django
9
- **Installation**: `pip install django-simple-captcha`
10
11
## Core Imports
12
13
```python
14
from captcha.fields import CaptchaField
15
```
16
17
For package version information:
18
19
```python
20
import captcha
21
print(captcha.VERSION) # (0, 6, 2)
22
print(captcha.get_version()) # "0.6.2"
23
```
24
25
For models and validation:
26
27
```python
28
from captcha.models import CaptchaStore
29
from captcha.validators import captcha_validate
30
```
31
32
For Django REST Framework integration:
33
34
```python
35
from captcha.serializers import CaptchaSerializer, CaptchaModelSerializer
36
```
37
38
## Basic Usage
39
40
```python
41
# Add to INSTALLED_APPS in settings.py
42
INSTALLED_APPS = [
43
# ... other apps
44
'captcha',
45
]
46
47
# Include captcha URLs in your main urls.py
48
from django.urls import path, include
49
50
urlpatterns = [
51
# ... other patterns
52
path('captcha/', include('captcha.urls')),
53
]
54
55
# Add captcha field to any Django form
56
from django import forms
57
from captcha.fields import CaptchaField
58
59
class ContactForm(forms.Form):
60
name = forms.CharField(max_length=100)
61
email = forms.EmailField()
62
message = forms.TextField()
63
captcha = CaptchaField()
64
65
# In your view
66
def contact_view(request):
67
if request.method == 'POST':
68
form = ContactForm(request.POST)
69
if form.is_valid():
70
# Process the form - captcha was validated automatically
71
pass
72
else:
73
form = ContactForm()
74
return render(request, 'contact.html', {'form': form})
75
```
76
77
## Architecture
78
79
Django Simple Captcha uses a multi-layered architecture:
80
81
- **Form Fields & Widgets**: `CaptchaField` and `CaptchaTextInput` provide Django form integration with automatic validation
82
- **Database Storage**: `CaptchaStore` model manages captcha challenges, responses, and expiration
83
- **View Layer**: Dedicated views serve captcha images, audio files, and AJAX refresh functionality
84
- **Challenge Generation**: Pluggable system for creating different types of challenges (math, random text, dictionary words)
85
- **Image Processing**: Configurable image generation with noise functions, filters, and styling options
86
- **REST Framework Integration**: Serializers for API-based captcha validation
87
88
## Capabilities
89
90
### Package Version Information
91
92
Package-level version constants and utility functions for version checking and display.
93
94
```python { .api }
95
VERSION = (0, 6, 2) # tuple, semantic version components
96
97
def get_version():
98
"""
99
Return the version as a human-format string.
100
101
Returns:
102
str: Version string like "0.6.2"
103
"""
104
```
105
106
### Form Integration
107
108
Core Django form integration with `CaptchaField` for automatic captcha validation, customizable widgets, and seamless form processing.
109
110
```python { .api }
111
class CaptchaField(MultiValueField):
112
def __init__(*args, **kwargs): ...
113
def clean(value): ...
114
115
class CaptchaTextInput(BaseCaptchaTextInput):
116
def __init__(attrs=None, id_prefix=None, generator=None): ...
117
def render(name, value, attrs=None, renderer=None): ...
118
```
119
120
[Form Integration](./form-integration.md)
121
122
### Models and Validation
123
124
Database model for captcha storage with expiration management, validation functions, and pool generation for performance optimization.
125
126
```python { .api }
127
class CaptchaStore(models.Model):
128
challenge = models.CharField(max_length=32)
129
response = models.CharField(max_length=32)
130
hashkey = models.CharField(max_length=40, unique=True)
131
expiration = models.DateTimeField()
132
133
@classmethod
134
def generate_key(generator=None): ...
135
@classmethod
136
def create_pool(count=1000): ...
137
138
def captcha_validate(hashkey, response): ...
139
```
140
141
[Models and Validation](./models-validation.md)
142
143
### Views and URLs
144
145
View functions for serving captcha images with customizable scaling, audio output for accessibility, and AJAX refresh functionality.
146
147
```python { .api }
148
def captcha_image(request, key, scale=1): ...
149
def captcha_audio(request, key): ...
150
def captcha_refresh(request): ...
151
```
152
153
[Views and URLs](./views-urls.md)
154
155
### Configuration and Customization
156
157
Comprehensive configuration system for customizing captcha appearance, challenge generation, noise functions, filters, and behavior.
158
159
```python { .api }
160
# Configuration constants
161
CAPTCHA_FONT_SIZE: int
162
CAPTCHA_LETTER_ROTATION: tuple
163
CAPTCHA_BACKGROUND_COLOR: str
164
CAPTCHA_CHALLENGE_FUNCT: str
165
CAPTCHA_NOISE_FUNCTIONS: tuple
166
CAPTCHA_TIMEOUT: int
167
168
# Challenge generators
169
def math_challenge(): ...
170
def random_char_challenge(): ...
171
def word_challenge(): ...
172
173
# Noise and filter functions
174
def noise_arcs(draw, image): ...
175
def noise_dots(draw, image): ...
176
def post_smooth(image): ...
177
```
178
179
[Configuration and Customization](./configuration.md)
180
181
### Django REST Framework Integration
182
183
Serializers for API-based captcha validation with both standalone and model-integrated serializers for REST API endpoints.
184
185
```python { .api }
186
class CaptchaSerializer(serializers.Serializer):
187
captcha_code = serializers.CharField(max_length=32, write_only=True, required=True)
188
captcha_hashkey = serializers.CharField(max_length=40, write_only=True, required=True)
189
190
def run_validation(data=empty): ...
191
192
class CaptchaModelSerializer(serializers.ModelSerializer):
193
captcha_code = serializers.CharField(max_length=32, write_only=True, required=True)
194
captcha_hashkey = serializers.CharField(max_length=40, write_only=True, required=True)
195
```
196
197
[Django REST Framework Integration](./rest-framework.md)
198
199
### Management Commands
200
201
Django management commands for captcha maintenance and optimization tasks.
202
203
```python { .api }
204
class Command(BaseCommand):
205
# captcha_clean command
206
def handle(**options):
207
"""
208
Clean up expired captcha records from database.
209
210
Parameters:
211
- options: dict, command options including verbosity
212
213
Returns:
214
None
215
"""
216
217
class Command(BaseCommand):
218
# captcha_create_pool command
219
def handle(**options):
220
"""
221
Create pool of captcha challenges for performance optimization.
222
223
Parameters:
224
- options: dict, including pool_size (int) and cleanup_expired (bool)
225
226
Returns:
227
None
228
"""
229
230
def add_arguments(parser):
231
"""
232
Add command-line arguments.
233
234
Parameters:
235
- parser: ArgumentParser instance
236
"""
237
238
# Usage examples:
239
# python manage.py captcha_clean
240
# python manage.py captcha_create_pool --pool-size=1000 --cleanup-expired
241
```