Skip to main content

django-sanitizer

A lightweight, configurable Django middleware that automatically sanitizes all incoming request data (JSON, form-data, query params) to protect your application against XSS, HTML injection, and unsafe attributes.

Built with Bleach, easy to install, easy to extend, and safe by default.


🛡 How It Works

The middleware intercepts the request before it reaches your views:

  1. Extracts request data (JSON, form-data, GET params)
  2. Sanitizes all values using allowed tags + attributes
  3. Places sanitized result in request.sanitized_data
  4. Your view receives only safe data

This allows cleaning without modifying Django internals.


🚀 Features

  • 🔒 Sanitizes JSON bodies, form-data, and query parameters
  • 🧼 Removes unsafe HTML tags, scripts, event handlers (e.g., onerror)
  • 🎯 Fully configurable via Django settings
  • 📝 Optional HTML response sanitization
  • 🛠 Zero configuration required — works out of the box
  • 🧪 Comes with testing utilities and easy middleware integration

📦 Installation

pip install django-sanitizer

Or install your local dev version:

pip install -e .

⚙️ Setup

Add the middleware to your Django settings:

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django_sanitizers.middleware.SanitizerMiddleware",
    "django.middleware.common.CommonMiddleware",
    ...
]

🔧 Configuration Options (Optional)

Add to settings.py only if you want customization:

SANITIZER_CONFIG = {
    # Define exactly which tags you want to KEEP
    'ALLOWED_TAGS': ['b', 'i', 'u', 'p', 'br'], 
    
    # Define allowed attributes (optional)
    'ALLOWED_ATTRIBUTES': {
        'a': ['href', 'title'],
        'img': ['src', 'alt']
    },
    
    # Security fields to skip
    'SKIP_FIELDS': {'password', 'password_confirmation', 'token', 'access_token', 'refresh_token','secret_key'},
    
    'STRIP': True
}

🧪 Example

Request Body:

{
  "bio": "<script>alert(1)</script><b>Hello</b>"
}

Sanitized Output:

{
  "bio": "<b>Hello</b>"
}

🧪 Django Views Example

JSON Example Endpoint

# views.py
from django.http import JsonResponse

def echo_json(request):
    return JsonResponse(request.sanitized_data)

Form Example Endpoint

def form_view(request):
    return JsonResponse(request.sanitized_data)

🧪 Testing in Postman

For JSON:

  • Method: POST
  • URL: /echo-json/
  • Headers: Content-Type: application/json
  • Body (raw JSON):
{"bio":"<img src=x onerror=alert(1)>hello"}

You should receive:

{"bio":"hello"}

📁 Project Structure (Package Only)

django_sanitizer/
│
├── __init__.py
├── sanitizer.py
└── middleware.py

🛠 Development

python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
pip install -e .

Run tests:

pytest

⭐ Support the Project

If this package helps you, please ⭐ star the repository on GitHub once published!

Metadata

Release files for django-sanitizers 0.1.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for django-sanitizers 0.1.3
File Size Uploaded
django_sanitizers-0.1.3.tar.gz 5.1 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for django-sanitizers 0.1.3
File Interpreter ABI Platform
django_sanitizers-0.1.3-py3-none-any.whl Python 3 none any Details

Total release size: 11.4 kB

Release files / django_sanitizers-0.1.3.tar.gz

Download URL django_sanitizers-0.1.3.tar.gz
Size 5.1 kB
Tags Source
SHA-256 checksum
How to use checksums
ce0568428ef05e02b4b1019bbb65f3976f2ea336f70cf23c26877dfab3e67e82
BLAKE2b-256 checksum
How to use checksums
cb564c38d0b3400a7d89db94a41ab52443f0a0f544b9727f4794c4287ae9c59a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.3

Release files / django_sanitizers-0.1.3-py3-none-any.whl

Download URL django_sanitizers-0.1.3-py3-none-any.whl
Size 6.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
206dd39234b02c9180c32653ce22bd79b843b542fc8ac5c0481d2fd4c39c7b29
BLAKE2b-256 checksum
How to use checksums
dacb77cc1961cea421ad8cebd2ab5a17023a74e1ee4b3b1a6f8f315c43bb326a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.3

Release history Release notifications | RSS feed

This release

0.1.3 This release

2 release files

0.1.2

2 release files

0.1.1

2 release files

0.0.1

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page