A very simple, yet powerful, Django captcha application for adding CAPTCHA image challenges to forms
npx @tessl/cli install tessl/pypi-django-simple-captcha@0.6.0A 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.
pip install django-simple-captchafrom captcha.fields import CaptchaFieldFor package version information:
import captcha
print(captcha.VERSION) # (0, 6, 2)
print(captcha.get_version()) # "0.6.2"For models and validation:
from captcha.models import CaptchaStore
from captcha.validators import captcha_validateFor Django REST Framework integration:
from captcha.serializers import CaptchaSerializer, CaptchaModelSerializer# Add to INSTALLED_APPS in settings.py
INSTALLED_APPS = [
# ... other apps
'captcha',
]
# Include captcha URLs in your main urls.py
from django.urls import path, include
urlpatterns = [
# ... other patterns
path('captcha/', include('captcha.urls')),
]
# Add captcha field to any Django form
from django import forms
from captcha.fields import CaptchaField
class ContactForm(forms.Form):
name = forms.CharField(max_length=100)
email = forms.EmailField()
message = forms.TextField()
captcha = CaptchaField()
# In your view
def contact_view(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
# Process the form - captcha was validated automatically
pass
else:
form = ContactForm()
return render(request, 'contact.html', {'form': form})Django Simple Captcha uses a multi-layered architecture:
CaptchaField and CaptchaTextInput provide Django form integration with automatic validationCaptchaStore model manages captcha challenges, responses, and expirationPackage-level version constants and utility functions for version checking and display.
VERSION = (0, 6, 2) # tuple, semantic version components
def get_version():
"""
Return the version as a human-format string.
Returns:
str: Version string like "0.6.2"
"""Core Django form integration with CaptchaField for automatic captcha validation, customizable widgets, and seamless form processing.
class CaptchaField(MultiValueField):
def __init__(*args, **kwargs): ...
def clean(value): ...
class CaptchaTextInput(BaseCaptchaTextInput):
def __init__(attrs=None, id_prefix=None, generator=None): ...
def render(name, value, attrs=None, renderer=None): ...Database model for captcha storage with expiration management, validation functions, and pool generation for performance optimization.
class CaptchaStore(models.Model):
challenge = models.CharField(max_length=32)
response = models.CharField(max_length=32)
hashkey = models.CharField(max_length=40, unique=True)
expiration = models.DateTimeField()
@classmethod
def generate_key(generator=None): ...
@classmethod
def create_pool(count=1000): ...
def captcha_validate(hashkey, response): ...View functions for serving captcha images with customizable scaling, audio output for accessibility, and AJAX refresh functionality.
def captcha_image(request, key, scale=1): ...
def captcha_audio(request, key): ...
def captcha_refresh(request): ...Comprehensive configuration system for customizing captcha appearance, challenge generation, noise functions, filters, and behavior.
# Configuration constants
CAPTCHA_FONT_SIZE: int
CAPTCHA_LETTER_ROTATION: tuple
CAPTCHA_BACKGROUND_COLOR: str
CAPTCHA_CHALLENGE_FUNCT: str
CAPTCHA_NOISE_FUNCTIONS: tuple
CAPTCHA_TIMEOUT: int
# Challenge generators
def math_challenge(): ...
def random_char_challenge(): ...
def word_challenge(): ...
# Noise and filter functions
def noise_arcs(draw, image): ...
def noise_dots(draw, image): ...
def post_smooth(image): ...Configuration and Customization
Serializers for API-based captcha validation with both standalone and model-integrated serializers for REST API endpoints.
class CaptchaSerializer(serializers.Serializer):
captcha_code = serializers.CharField(max_length=32, write_only=True, required=True)
captcha_hashkey = serializers.CharField(max_length=40, write_only=True, required=True)
def run_validation(data=empty): ...
class CaptchaModelSerializer(serializers.ModelSerializer):
captcha_code = serializers.CharField(max_length=32, write_only=True, required=True)
captcha_hashkey = serializers.CharField(max_length=40, write_only=True, required=True)Django REST Framework Integration
Django management commands for captcha maintenance and optimization tasks.
class Command(BaseCommand):
# captcha_clean command
def handle(**options):
"""
Clean up expired captcha records from database.
Parameters:
- options: dict, command options including verbosity
Returns:
None
"""
class Command(BaseCommand):
# captcha_create_pool command
def handle(**options):
"""
Create pool of captcha challenges for performance optimization.
Parameters:
- options: dict, including pool_size (int) and cleanup_expired (bool)
Returns:
None
"""
def add_arguments(parser):
"""
Add command-line arguments.
Parameters:
- parser: ArgumentParser instance
"""
# Usage examples:
# python manage.py captcha_clean
# python manage.py captcha_create_pool --pool-size=1000 --cleanup-expired