Registry / web-framework / django-csp

django-csp

JSON →
library4.0pypypi✓ verified 28d ago

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.

pip install django-csp
INSTALL
IMPORT
SIG · DJANGO-CSP
D
django-csp
web-frameworkpythonv4.0
Install
3.6s avg
Import
273ms
Disk
67MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.9–3.13
musl
3.9–3.13
Install & Compatibility
Where this runs
tested against v4.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.10–3.95 runs
installs and imports cleanly · install 0.0s · import 0.282s · 67.5MB
glibc
py 3.10–3.95 runs
installs and imports cleanly · install 3.6s · import 0.264s · 68MB
67MB installed
● package 67MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

CSPMiddleware
✓ from csp.middleware import CSPMiddleware
CSPReportMiddleware
✓ from csp.middleware import CSPReportMiddleware
nonce
✓ from csp.utils import nonce
CSPMiddlewareAlwaysGenerateNonce
✓ N/A
✗ from csp.middleware import CSPMiddlewareAlwaysGenerateNonce
Removed in v4.0; use CSP_AUTO_NONCE or CSP_NONCE_URL_PREFIXES instead.

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>
Debug
Known issues
breakingThe configuration format changed significantly in v4.0. Old `CSP_` prefixed settings (e.g., `CSP_DEFAULT_SRC`, `CSP_REPORT_ONLY`) are removed. Policies must now be defined using dictionaries `CONTENT_SECURITY_POLICY` and `CONTENT_SECURITY_POLICY_REPORT_ONLY`.
fix
Migrate your CSP settings to the new dictionary-based format. Consult the official migration guide for v4.0.
affects: 4.0+
breakingThe `CSPMiddlewareAlwaysGenerateNonce` middleware and the `CSP_ALWAYS_GENERATE_NONCE` setting were removed in v4.0. Nonce generation is now controlled by `CSP_AUTO_NONCE` or `CSP_NONCE_URL_PREFIXES`.
fix
Remove `CSPMiddlewareAlwaysGenerateNonce` from your `MIDDLEWARE` list and rely on `CSP_AUTO_NONCE = True` (in settings) or `CSP_NONCE_URL_PREFIXES` for automatic nonce generation.
affects: 4.0+
gotchaFor nonce-based CSP, inline scripts and styles require the `nonce` attribute. While `CSP_AUTO_NONCE = True` generates a nonce, you *must* use the `{% csp_nonce %}` template tag to apply it to your inline elements.
fix
Ensure `{% load csp %}` is present in your template, and apply `nonce="{% csp_nonce %}"` to all inline `<script>` and `<style>` tags that should be allowed by your CSP.
affects: 3.x, 4.0+
gotchaIf you use the `report-uri` directive with `CSP_REPORT_PERCENTAGE`, you should implement rate limiting on the `/csp-report/` endpoint to prevent abuse and denial-of-service attacks, as browsers may send many reports.
fix
Integrate a rate-limiting middleware (e.g., `django-ratelimit`) or a proxy-level rate limiter to protect your CSP report endpoint.
affects: 3.x, 4.0+
Errors
Common errors & fixes
CSP_DEFAULT_SRC = ("'self'",)
In django-csp 4.0, the configuration format for Content Security Policy settings was updated, deprecating individual `CSP_XXX` prefixed settings in favor of dictionary-based `CONTENT_SECURITY_POLICY` and `CONTENT_SECURITY_POLICY_REPORT_ONLY` settings.
fix
Migrate your `settings.py` to use the new dictionary format. For example, change `CSP_DEFAULT_SRC = ("'self'",)` to `CONTENT_SECURITY_POLICY = { "DIRECTIVES": { "default-src": ["'self'"] } }` and remove all old `CSP_XXX` settings.
Refused to execute a script because its hash, its nonce, or 'unsafe-inline' does not appear in the script-src directive of the Content Security Policy.
The Content Security Policy defined by django-csp is blocking inline scripts (or styles) because the `script-src` (or `style-src`) directive does not explicitly allow them via a cryptographic hash, a dynamically generated nonce, or the less secure `'unsafe-inline'` keyword.
fix
To fix this, include `csp.constants.NONCE` in the relevant directives (e.g., `script-src`) in your `CONTENT_SECURITY_POLICY` setting, add `csp.context_processors.nonce` to your `TEMPLATES` `context_processors`, and include `nonce="{{ request.csp_nonce }}"` in your inline `<script>` or `<style>` tags. Alternatively, for less secure scenarios, add `'unsafe-inline'` to the directive.
ModuleNotFoundError: No module named 'csp'
The `django-csp` package is either not installed in your Python environment, or the `csp` application has not been added to your Django project's `INSTALLED_APPS` setting.
fix
First, ensure `django-csp` is installed using `pip install django-csp`. Then, add `'csp'` to your `INSTALLED_APPS` list in your Django project's `settings.py` file.
ModuleNotFoundError: No module named 'django.utils.six'
This error occurs when an older version of `django-csp` (or one of its dependencies) is used with Django 3.0 or newer, as `django.utils.six` was removed in Django 3.0.
fix
Upgrade your `django-csp` package to version 3.0 or newer, which is compatible with Django 3.0+ and removes the dependency on `django.utils.six`.
Upgrade
Version history
4.0latest on PyPI · released Apr 2, 2025
Audit
Dependencies

No dependency data recorded yet.

Agent activity
32 hits · last 30 days
node
26
OpenAI (training)
1
Resources
django-csp — pip install django-csp · libregistry