Django Simple CAPTCHA

0.6.3 · active · verified Thu Apr 16

django-simple-captcha is a robust yet easy-to-use Django application for integrating CAPTCHA into forms. It supports various CAPTCHA types including image and audio. Currently at version 0.6.3, it is actively maintained with regular updates to support new Django versions and address user feedback.

Common errors

Warnings

Install

Imports

Quickstart

To integrate django-simple-captcha, first add 'captcha' to your `INSTALLED_APPS` in `settings.py`. Then, include `path('captcha/', include('captcha.urls'))` in your project's `urls.py`. Finally, define a form using `captcha.fields.CaptchaField` and render it in your templates.

import os
import django
from django.conf import settings

# Minimal Django setup for demonstration
if not settings.configured:
    settings.configure(
        INSTALLED_APPS=['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'captcha'],
        MIDDLEWARE=[
            'django.middleware.security.SecurityMiddleware',
            'django.contrib.sessions.middleware.SessionMiddleware',
            'django.middleware.common.CommonMiddleware',
            'django.middleware.csrf.CsrfViewMiddleware',
            'django.contrib.auth.middleware.AuthenticationMiddleware',
            'django.contrib.messages.middleware.MessageMiddleware',
            'django.middleware.clickjacking.XFrameOptionsMiddleware',
        ],
        ROOT_URLCONF='__main__',
        TEMPLATES=[
            {
                'BACKEND': 'django.template.backends.django.DjangoTemplates',
                'DIRS': [],
                'APP_DIRS': True,
                'OPTIONS': {
                    'context_processors': [
                        'django.template.context_processors.debug',
                        'django.template.context_processors.request',
                        'django.contrib.auth.context_processors.auth',
                        'django.contrib.messages.context_processors.messages',
                    ],
                },
            },
        ],
        DATABASES={'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:'}},
        SECRET_KEY=os.environ.get('DJANGO_SECRET_KEY', 'a-very-secret-key-for-testing-only'),
        STATIC_URL='/static/',
        DEBUG=True
    )

django.setup()

from django import forms
from django.http import HttpResponse
from django.urls import path, include
from django.views.generic import FormView
from captcha.fields import CaptchaField

class ContactForm(forms.Form):
    subject = forms.CharField(max_length=100)
    message = forms.CharField(widget=forms.Textarea)
    captcha = CaptchaField()

class ContactView(FormView):
    template_name = 'form_template.html' # In a real app, this would be a file
    form_class = ContactForm
    success_url = '/success/'

    def form_valid(self, form):
        # Process the form data (e.g., send email)
        print("Form is valid! Subject:", form.cleaned_data['subject'])
        return super().form_valid(form)

    def get(self, request, *args, **kwargs):
        # For quickstart, just render the form without a real template
        form = self.get_form()
        html = f"""
            <form method="post">
                <p>{{ form.subject.label_tag }} {{ form.subject }}</p>
                <p>{{ form.message.label_tag }} {{ form.message }}</p>
                <p>{{ form.captcha.label_tag }} {{ form.captcha }}</p>
                <button type="submit">Submit</button>
                {% csrf_token %}
            </form>
        """
        return HttpResponse(html.replace('{% csrf_token %}', request.META.get('CSRF_COOKIE', '')))

    def post(self, request, *args, **kwargs):
        form = self.get_form()
        if form.is_valid():
            return self.form_valid(form)
        else:
            return HttpResponse("Form invalid! " + str(form.errors))

urlpatterns = [
    path('', ContactView.as_view(), name='contact'),
    path('captcha/', include('captcha.urls')),
    path('success/', lambda request: HttpResponse('Form submitted successfully! CAPTCHA was valid.')),
]

# To run this minimal example (requires a test runner or manual URL dispatch)
# from django.urls import resolve
# from django.test import RequestFactory
# 
# factory = RequestFactory()
# 
# # Test GET request
# request = factory.get('/')
# response = resolve('/').func(request)
# print("\nGET Response:", response.status_code, response.content.decode()[:200], "...")
# 
# # Test POST request (replace with actual CAPTCHA values from GET request if needed)
# # This part is tricky to automate without actually solving the captcha.
# # You would typically submit a solved captcha value. 
# # Example POST data, assuming 'captcha_0' is the key for the hash, 'captcha_1' for the response:
# # post_data = {'subject': 'Test Subject', 'message': 'Test Message', 'captcha_0': 'hash_value', 'captcha_1': 'solved_text'}
# # request = factory.post('/', post_data)
# # response = resolve('/').func(request)
# # print("\nPOST Response:", response.status_code, response.content.decode()[:200], "...")

print("Setup complete. You would normally run this via `manage.py runserver`.")
print("To access the form, configure your Django project's urls.py with `path('captcha/', include('captcha.urls'))` and `path('', views.ContactView.as_view())`")

view raw JSON →