Skip to main content

A Django middleware that sanitizes incoming request data to prevent XSS.

Project description

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_ENABLED = True
SANITIZER_ALLOWED_TAGS = ["b", "i", "u", "em", "strong", "a", "br", "p", "ul", "ol", "li",]
SANITIZER_ALLOWED_ATTRIBUTES = {"a": ["href", "title", "rel"]}
SANITIZER_STRIP = True
SANITIZER_SANITIZE_RESPONSE_HTML = False
SANITIZER_DEBUG = True
SANITIZER_SKIP_FIELDS = {'password', 'password_confirmation', 'token', 'access_token', 'refresh_token','secret_key'} # CRITICAL: If this line is missing or empty, no fields will be skipped.

🧪 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!

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django_sanitizers-0.1.2.tar.gz (5.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

django_sanitizers-0.1.2-py3-none-any.whl (6.2 kB view details)

Uploaded Python 3

File details

Details for the file django_sanitizers-0.1.2.tar.gz.

File metadata

  • Download URL: django_sanitizers-0.1.2.tar.gz
  • Upload date:
  • Size: 5.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.3

File hashes

Hashes for django_sanitizers-0.1.2.tar.gz
Algorithm Hash digest
SHA256 f5e1e9c8055cdb84aa15b18fa34a5e3dcc0c6b44e2d6aaab8bb3c15a0a9d684b
MD5 f767f971d1cc495b765a6d5ccc7f7dae
BLAKE2b-256 88d092f7d6e0816154cba5719f318be73c4defb94e263d912237ab6f85e3c1d5

See more details on using hashes here.

File details

Details for the file django_sanitizers-0.1.2-py3-none-any.whl.

File metadata

File hashes

Hashes for django_sanitizers-0.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 1ed742c33814bf7ad4ac234f0a36ce48f43d7357ffe7726e432c9fbe607c0689
MD5 f80c62556a4f026b17060c33bd1435a7
BLAKE2b-256 03cfb360cb88a3573667b0aeea62c18067a0e17520f8d5ce1df0709aff4f6408

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page