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.1.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.1-py3-none-any.whl (6.2 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: django_sanitizers-0.1.1.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.1.tar.gz
Algorithm Hash digest
SHA256 fb81060781c8b1295ab00f2b6bcf482ca29ada65d25ef702d9696b69f0aa20f7
MD5 b0cd1438a73a47b6b160a657d4839d51
BLAKE2b-256 6532ee7e3b030e99c072d00a4b88774beea9226aa324d9b8accc14ed418700fc

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for django_sanitizers-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 df48ba85975691834935cb69c9ffd9c4a90238ecaabe575195a15d12fa321186
MD5 076866f32eb9dbd6ebc50c1ed11e8396
BLAKE2b-256 b506dc4bb72882888b269fe9731755498f7d571345f14c7f6fea59e118f6b59f

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