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:
- Extracts request data (JSON, form-data, GET params)
- Sanitizes all values using allowed tags + attributes
- Places sanitized result in
request.sanitized_data
- 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 = {
'ALLOWED_TAGS': ['b', 'i', 'u', 'p', 'br'],
'ALLOWED_ATTRIBUTES': {
'a': ['href', 'title'],
'img': ['src', 'alt']
},
'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
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!