Django CSP

4.0 · active · verified Fri Apr 10

django-csp provides robust Content Security Policy (CSP) support for Django applications. It helps mitigate cross-site scripting (XSS) and other code injection attacks by adding CSP headers to HTTP responses. The latest major version is 4.0, which introduced significant breaking changes to its configuration format. The project is actively maintained, typically releasing updates to support new Django and Python versions.

Warnings

Install

Imports

Quickstart

To integrate django-csp, add `csp` to `INSTALLED_APPS` and `CSPMiddleware` to your `MIDDLEWARE` list. Define your Content Security Policy directives using the `CONTENT_SECURITY_POLICY` dictionary in `settings.py`. For nonce-based policies, set `CSP_AUTO_NONCE = True` and use the `{% csp_nonce %}` template tag for inline scripts and styles.

# settings.py

INSTALLED_APPS = [
    # ...
    "csp",
]

MIDDLEWARE = [
    # ...
    "csp.middleware.CSPMiddleware",
    # Optionally, for reporting only:
    # "csp.middleware.CSPReportMiddleware",
    # ...
]

# Basic CSP policy, enforce for all pages by default
CONTENT_SECURITY_POLICY = {
    "default-src": ["'self'"],
    "script-src": ["'self'", "'unsafe-inline'", "'unsafe-eval'", "'nonce-{{ nonce }}'"],
    "style-src": ["'self'", "'unsafe-inline'", "'nonce-{{ nonce }}'"],
    "img-src": ["'self'", "data:", "https://example.com"],
    "report-uri": ["/csp-report/"],
}

# To enable automatic nonce generation (recommended for inline scripts/styles)
CSP_AUTO_NONCE = True

# urls.py

from django.urls import path
from django.views.decorators.csrf import csrf_exempt
from csp.views import report

urlpatterns = [
    # Your other URLs...
    path("csp-report/", csrf_exempt(report), name="csp-report"),
]

# In your templates (e.g., base.html) to apply nonce to inline elements:
# {% load csp %}
# <script nonce="{% csp_nonce %}">...</script>
# <style nonce="{% csp_nonce %}">...</style>

view raw JSON →