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-cspVerified import paths — ran on the pinned version, not inferred.
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.
Migrate your CSP settings to the new dictionary-based format. Consult the official migration guide for v4.0.
Remove `CSPMiddlewareAlwaysGenerateNonce` from your `MIDDLEWARE` list and rely on `CSP_AUTO_NONCE = True` (in settings) or `CSP_NONCE_URL_PREFIXES` for automatic nonce generation.
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.Integrate a rate-limiting middleware (e.g., `django-ratelimit`) or a proxy-level rate limiter to protect your CSP report endpoint.
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.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.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.
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`.
No dependency data recorded yet.