{"id":2475,"library":"django-csp","title":"Django CSP","description":"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.","status":"active","version":"4.0","language":"python","source_language":"en","source_url":"https://github.com/mozilla/django-csp","tags":["django","security","csp","content-security-policy","middleware"],"install":[{"cmd":"pip install django-csp","lang":"bash","label":"Install stable version"}],"dependencies":[],"imports":[{"symbol":"CSPMiddleware","correct":"from csp.middleware import CSPMiddleware"},{"symbol":"CSPReportMiddleware","correct":"from csp.middleware import CSPReportMiddleware"},{"symbol":"nonce","correct":"from csp.utils import nonce"},{"note":"Removed in v4.0; use CSP_AUTO_NONCE or CSP_NONCE_URL_PREFIXES instead.","wrong":"from csp.middleware import CSPMiddlewareAlwaysGenerateNonce","symbol":"CSPMiddlewareAlwaysGenerateNonce","correct":"N/A"}],"quickstart":{"code":"# settings.py\n\nINSTALLED_APPS = [\n    # ...\n    \"csp\",\n]\n\nMIDDLEWARE = [\n    # ...\n    \"csp.middleware.CSPMiddleware\",\n    # Optionally, for reporting only:\n    # \"csp.middleware.CSPReportMiddleware\",\n    # ...\n]\n\n# Basic CSP policy, enforce for all pages by default\nCONTENT_SECURITY_POLICY = {\n    \"default-src\": [\"'self'\"],\n    \"script-src\": [\"'self'\", \"'unsafe-inline'\", \"'unsafe-eval'\", \"'nonce-{{ nonce }}'\"],\n    \"style-src\": [\"'self'\", \"'unsafe-inline'\", \"'nonce-{{ nonce }}'\"],\n    \"img-src\": [\"'self'\", \"data:\", \"https://example.com\"],\n    \"report-uri\": [\"/csp-report/\"],\n}\n\n# To enable automatic nonce generation (recommended for inline scripts/styles)\nCSP_AUTO_NONCE = True\n\n# urls.py\n\nfrom django.urls import path\nfrom django.views.decorators.csrf import csrf_exempt\nfrom csp.views import report\n\nurlpatterns = [\n    # Your other URLs...\n    path(\"csp-report/\", csrf_exempt(report), name=\"csp-report\"),\n]\n\n# In your templates (e.g., base.html) to apply nonce to inline elements:\n# {% load csp %}\n# <script nonce=\"{% csp_nonce %}\">...</script>\n# <style nonce=\"{% csp_nonce %}\">...</style>","lang":"python","description":"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."},"warnings":[{"fix":"Migrate your CSP settings to the new dictionary-based format. Consult the official migration guide for v4.0.","message":"The 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`.","severity":"breaking","affected_versions":"4.0+"},{"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.","message":"The `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`.","severity":"breaking","affected_versions":"4.0+"},{"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.","message":"For 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.","severity":"gotcha","affected_versions":"3.x, 4.0+"},{"fix":"Integrate a rate-limiting middleware (e.g., `django-ratelimit`) or a proxy-level rate limiter to protect your CSP report endpoint.","message":"If 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.","severity":"gotcha","affected_versions":"3.x, 4.0+"}],"env_vars":null,"search_vec":"'4.0':41 'activ':54 'ad':30 'applic':15 'attack':28 'break':45 'chang':46 'code':26 'configur':49 'content':8,70 'content-security-polici':69 'cross':20 'cross-sit':19 'csp':2,5,11,31,68 'django':1,4,14,62,66 'django-csp':3 'format':50 'header':32 'help':17 'http':34 'inject':27 'introduc':43 'latest':37 'maintain':55 'major':38 'middlewar':73 'mitig':18 'new':61 'polici':10,72 'project':52 'provid':6 'python':64 'releas':57 'respons':35 'robust':7 'script':22 'secur':9,67,71 'signific':44 'site':21 'support':12,60 'typic':56 'updat':58 'version':39,65 'xss':23","created_at":"2026-04-11T01:29:42.209531+00:00","updated_at":"2026-04-16T14:29:45.838387+00:00","problems":[{"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.","cause":"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.","error":"CSP_DEFAULT_SRC = (\"'self'\",)"},{"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.","cause":"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.","error":"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."},{"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.","cause":"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.","error":"ModuleNotFoundError: No module named 'csp'"},{"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`.","cause":"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.","error":"ModuleNotFoundError: No module named 'django.utils.six'"}],"ecosystem":"pypi","meta_description":null,"install_score":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":"4.0","cli_name":"","cli_version":null,"type":"library","homepage":null,"github":"https://github.com/mozilla/django-csp","docs":"http://django-csp.readthedocs.org/","changelog":"https://github.com/mozilla/django-csp/blob/main/CHANGES.md","pypi":"https://pypi.org/project/django-csp/","npm":null,"openapi_spec":null,"status_page":null,"smithery":null,"categories":["web-framework","auth-security","aws","gcp","azure"],"base_url":null,"auth_type":null,"provenance":{"verified_status":"passing","verified_at":"2026-06-28","last_verified":"2026-08-28","next_check":"2026-07-28","install_tag":null}}