ZetCode

Django Content Security Policy

last modified November 21, 2026 Python 3.15

Django escapes the variables in templates, which stops most cross-site scripting (XSS) attacks. A Content Security Policy (CSP) is a second line of defence: an HTTP header that tells the browser from which sources a page may load scripts, styles, images, frames, and other resources. If an attacker manages to inject a <script> tag, the browser refuses to run it because it does not come from an allowed source. Since version 6.0 Django supports CSP out of the box. In this article we add a policy to a page and watch what the browser blocks, allow inline code with nonces, test a stricter policy in report-only mode, collect the violation reports, change the policy for single views, and write tests. The examples use Django 6.1 and Python 3.15 and were checked in Chrome.

Directives and sources

A policy is a list of directives separated by semicolons. Each directive names a kind of resource and lists its allowed sources, for example script-src 'self' https://cdn.example.com. The directive default-src applies to every kind of resource that has no directive of its own. Sources are host names and schemes such as https: or data:, and keywords in single quotes: 'self' is the origin of the page, 'none' allows nothing, and 'unsafe-inline' allows inline scripts and styles, which defeats much of the purpose. A policy in the header Content-Security-Policy is enforced; the same policy in Content-Security-Policy-Report-Only blocks nothing and only reports what it would block.

The example project

The project is created with uv; the steps are explained in Django introduction. The commands below create a project directory, install Django, generate the project with the configuration package config, start the app pages, and create the folder demos for demo scripts.

$ mkdir csp
$ cd csp
$ uv init --bare
$ uv add django
$ uv run django-admin startproject config .
$ uv run python manage.py startapp pages
$ mkdir demos

The trailing dot in startproject config . creates manage.py and the config package in the current directory instead of one level deeper. A new app is ignored by Django until it is listed in INSTALLED_APPS, so we add the app to the list in config/settings.py; the other entries are generated by startproject.

config/settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'pages',
]

The listings in this article are of two kinds. A listing with a solid blue border and the label Project file is a file of the application: models, views, templates, tests, and settings. A listing with a dashed amber border and the label Demo script is a small helper in the demos folder; it sets up Django, runs a few lines of code, and prints the results, so that we can watch the behaviour. Demo scripts are not part of the application; we run one from the project directory with uv run python -m demos.name.

The CSP support has two parts that we enable now. The middleware ContentSecurityPolicyMiddleware adds the headers to the responses, and the context processor csp makes the nonce, explained later, available in templates. The enumeration CSP holds the keywords with their quotes, so that we write CSP.SELF instead of "'self'".

config/settings.py (CSP)
from pathlib import Path

from django.utils.csp import CSP

...

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.middleware.csp.ContentSecurityPolicyMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    ...
]

...

TEMPLATES = [
    {
        ...
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.csp',
                'django.template.context_processors.request',
                ...
            ],
        },
    },
]

The middleware does nothing until a policy is configured, which we do in a moment.

A page with scripts and styles

The test page uses four kinds of resources: an external style sheet and an external script, both served from the site, and an inline style and an inline script in the HTML. The style sheet sets the font and colours the status words.

pages/static/pages/site.css
body {
    font-family: sans-serif;
    margin: 1.5em;
}

b {
    color: #b00020;
}

The external script writes ran into the first status.

pages/static/pages/app.js
document.getElementById('external').textContent = 'ran';

The template shows blocked for both scripts; each script replaces its word when it runs. The inline style makes the heading green.

pages/templates/pages/home.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Content Security Policy</title>
<link rel="stylesheet" href="{% static 'pages/site.css' %}">
<style>
  h1 { color: darkgreen; }
</style>
</head>
<body>
<h1>Content Security Policy</h1>
<ul>
<li>external script: <b id="external">blocked</b></li>
<li>inline script: <b id="inline">blocked</b></li>
</ul>
<script src="{% static 'pages/app.js' %}"></script>
<script>
  document.getElementById('inline').textContent = 'ran';
</script>
</body>
</html>

The view renders the template.

pages/views.py
from django.shortcuts import render


def home(request):
    return render(request, 'pages/home.html')

The app's URL configuration maps the view to the root path.

pages/urls.py
from django.urls import path

from . import views

urlpatterns = [
    path('', views.home, name='home'),
]

The project includes the URLs of the app.

config/urls.py
from django.urls import include, path

urlpatterns = [
    path('', include('pages.urls')),
]

We start the development server, which also serves the static files.

$ uv run python manage.py runserver

Without a policy the browser runs both scripts and applies the inline style. The headers contain the security headers that Django adds by default, but no Content-Security-Policy.

$ curl -sI localhost:8000/
HTTP/1.1 200 OK
Date: Sat, 21 Nov 2026 16:26:21 GMT
Server: WSGIServer CPython/3.15.2
Content-Type: text/html; charset=utf-8
X-Frame-Options: DENY
Content-Length: 503
X-Content-Type-Options: nosniff
Referrer-Policy: same-origin
Cross-Origin-Opener-Policy: same-origin

The first policy

The setting SECURE_CSP is a dictionary that maps directives to lists of sources. The simplest useful policy allows everything from the origin of the site and nothing else. We add it at the end of the settings.

config/settings.py (policy)
# Content Security Policy
SECURE_CSP = {
    'default-src': [CSP.SELF],
}

The browser now loads the style sheet and runs the external script, because both come from 'self', but it refuses the inline script and the inline style: the status stays blocked and the heading is black. The console of the browser explains each refusal, for example Refused to execute inline script because it violates the following Content Security Policy directive: "default-src 'self'". That is the protection against XSS: an injected script is inline too.

The page with the inline script and style blocked
Figure: The inline script and style are blocked

The response carries the policy in the header.

$ curl -sI localhost:8000/ | grep -i content-security
Content-Security-Policy: default-src 'self'

The policy must be a dictionary. A policy written as a string, SECURE_CSP = "default-src 'self'", is caught by the system checks.

$ uv run python manage.py check 2>&1
SystemCheckError: System check identified some issues:

ERRORS:
?: (security.E026) The Content Security Policy setting 'SECURE_CSP' must be a dictionary (got "default-src 'self'" instead).

System check identified 1 issue (0 silenced).

Nonces for inline code

The best fix for inline code is to move it into files. When that is not practical, a nonce allows selected inline elements: a random value, new for every response, that appears both in the policy and in the attribute nonce of the elements. An attacker who injects a script cannot know the value. The placeholder CSP.NONCE in a directive is replaced by the middleware with the nonce of the request.

config/settings.py (policy)
# Content Security Policy
SECURE_CSP = {
    'default-src': [CSP.SELF],
    'script-src': [CSP.SELF, CSP.NONCE],
    'style-src': [CSP.SELF, CSP.NONCE],
}

The context processor puts the nonce into templates as csp_nonce. The inline <style> and <script> elements get it in their nonce attribute; nothing else changes in the template.

pages/templates/pages/home.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Content Security Policy</title>
<link rel="stylesheet" href="{% static 'pages/site.css' %}">
<style nonce="{{ csp_nonce }}">
  h1 { color: darkgreen; }
</style>
</head>
<body>
<h1>Content Security Policy</h1>
<ul>
<li>external script: <b id="external">blocked</b></li>
<li>inline script: <b id="inline">blocked</b></li>
</ul>
<script src="{% static 'pages/app.js' %}"></script>
<script nonce="{{ csp_nonce }}">
  document.getElementById('inline').textContent = 'ran';
</script>
</body>
</html>

We add a second view that returns plain text and uses no template, to see what happens when no nonce is needed.

pages/views.py
from django.http import HttpResponse
from django.shortcuts import render


def home(request):
    return render(request, 'pages/home.html')


def status(request):
    return HttpResponse('ok', content_type='text/plain')

The new view gets the path status/.

pages/urls.py
from django.urls import path

from . import views

urlpatterns = [
    path('', views.home, name='home'),
    path('status/', views.status, name='status'),
]

In the browser everything runs again: the inline script has the right nonce and the heading is green.

The page with the nonces, everything runs
Figure: With nonces the inline script and style are allowed

The demo script requests the page twice with the test client, compares the nonce in the header with the attributes in the HTML, and prints the policies of both views.

demos/nonce.py
import os
import re

import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()

from django.test import Client
from django.test.utils import setup_test_environment

setup_test_environment()

client = Client()
for number in range(2):
    response = client.get('/')
    policy = response['Content-Security-Policy']
    header_nonces = set(re.findall(r"'nonce-([^']+)'", policy))
    page_nonces = set(re.findall(r'nonce="([^"]+)"', response.content.decode()))
    print(f'request {number + 1}: nonce {header_nonces}, same in the page: {header_nonces == page_nonces}')

print('policy of /:      ', client.get('/')['Content-Security-Policy'])
print('policy of status/:', client.get('/status/')['Content-Security-Policy'])

Each response has a different nonce, and the page uses the one from its header. The nonce is generated lazily, only when something reads it; the plain text view never does, so its policy has no nonce at all. The curl request shows the attributes in the HTML. Django 6.1 also has the template tag {% csp_nonce_attr %}, which writes the whole attribute.

$ uv run python -m demos.nonce
request 1: nonce {'_ztUwPjhKFqaksJthhyxIw'}, same in the page: True
request 2: nonce {'vDUv1fNc5iwziRUYnOpsYQ'}, same in the page: True
policy of /:       default-src 'self'; script-src 'self' 'nonce-Z794_EUsP56ruPZCTQAEfw'; style-src 'self' 'nonce-Z794_EUsP56ruPZCTQAEfw'
policy of status/: default-src 'self'; script-src 'self'; style-src 'self'
$ curl -s localhost:8000/ | grep nonce
<style nonce="_KJrSI8WrmzmyQ1OMZwFxQ">
<script nonce="_KJrSI8WrmzmyQ1OMZwFxQ">

Report-only policies and violation reports

A strict policy can break a site in ways that are hard to predict. The setting SECURE_CSP_REPORT_ONLY sends a second policy in the header Content-Security-Policy-Report-Only: the browser blocks nothing for it, but reports what it would have blocked. The directive report-uri tells the browser where to send the reports, as JSON documents in a POST request. We store them in a model.

pages/models.py
from django.db import models


class ViolationReport(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    disposition = models.CharField(max_length=10)
    directive = models.CharField(max_length=40)
    blocked_uri = models.CharField(max_length=200)
    document_uri = models.CharField(max_length=200)
    sample = models.CharField(max_length=100, blank=True)

    def __str__(self):
        return f'{self.disposition} {self.directive} {self.blocked_uri}'

We create the table.

$ uv run python manage.py makemigrations pages
Migrations for 'pages':
  pages/migrations/0001_initial.py
    + Create model ViolationReport
$ uv run python manage.py migrate | tail -n 2
  Applying pages.0001_initial... OK
  Applying sessions.0001_initial... OK

The view csp_report parses the report, saves the interesting fields, and answers with the status 204. The browser does not send a CSRF token, so the view is exempt from the CSRF check, and since anyone can post to it, it accepts only valid JSON and cuts the fields to the lengths of the columns.

pages/views.py
import json

from django.http import HttpResponse, HttpResponseBadRequest
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST

from .models import ViolationReport


def home(request):
    return render(request, 'pages/home.html')


def status(request):
    return HttpResponse('ok', content_type='text/plain')


@csrf_exempt
@require_POST
def csp_report(request):
    try:
        report = json.loads(request.body)['csp-report']
    except (ValueError, KeyError, TypeError):
        return HttpResponseBadRequest('invalid report')

    ViolationReport.objects.create(
        disposition=report.get('disposition', '')[:10],
        directive=report.get('effective-directive', '')[:40],
        blocked_uri=report.get('blocked-uri', '')[:200],
        document_uri=report.get('document-uri', '')[:200],
        sample=report.get('script-sample', '')[:100],
    )
    return HttpResponse(status=204)

The report view gets its own path.

pages/urls.py
from django.urls import path

from . import views

urlpatterns = [
    path('', views.home, name='home'),
    path('status/', views.status, name='status'),
    path('csp-report/', views.csp_report, name='csp_report'),
]

The enforced policy now allows images from data: URLs and asks for reports; CSP.REPORT_SAMPLE makes the browser include the first characters of a blocked script. The report-only policy is the stricter one that we would like to enforce one day: it starts from 'none', allows images only from the site, and adds base-uri, form-action, and frame-ancestors, which default-src does not cover. The newer directive report-to, which needs the header Reporting-Endpoints, can replace report-uri; browsers still support both.

config/settings.py (policy)
# Content Security Policy
SECURE_CSP = {
    'default-src': [CSP.SELF],
    'script-src': [CSP.SELF, CSP.NONCE, CSP.REPORT_SAMPLE],
    'style-src': [CSP.SELF, CSP.NONCE],
    'img-src': [CSP.SELF, 'data:'],
    'report-uri': '/csp-report/',
}

SECURE_CSP_REPORT_ONLY = {
    'default-src': [CSP.NONE],
    'script-src': [CSP.SELF, CSP.NONCE, CSP.REPORT_SAMPLE],
    'style-src': [CSP.SELF, CSP.NONCE],
    'img-src': [CSP.SELF],
    'base-uri': [CSP.NONE],
    'form-action': [CSP.SELF],
    'frame-ancestors': [CSP.NONE],
    'report-uri': '/csp-report/',
}

The template gets an image with a data: URL and a button with an inline event handler in the attribute onclick. A nonce cannot be given to an event handler, so this is code that must be moved into a script file.

pages/templates/pages/home.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Content Security Policy</title>
<link rel="stylesheet" href="{% static 'pages/site.css' %}">
<style nonce="{{ csp_nonce }}">
  h1 { color: darkgreen; }
</style>
</head>
<body>
<h1>Content Security Policy</h1>
<ul>
<li>external script: <b id="external">blocked</b></li>
<li>inline script: <b id="inline">blocked</b></li>
</ul>
<p>
<img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='120' height='12'%3E%3Crect width='120' height='12' fill='steelblue'/%3E%3C/svg%3E" alt="bar">
</p>
<button onclick="this.textContent = 'clicked'">Click me</button>
<script src="{% static 'pages/app.js' %}"></script>
<script nonce="{{ csp_nonce }}">
  document.getElementById('inline').textContent = 'ran';
</script>
</body>
</html>

After a restart the responses carry both headers.

$ curl -sI localhost:8000/ | grep -i content-security
Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-hvEIsGfztyq1BNzCGx94sQ' 'report-sample'; style-src 'self' 'nonce-hvEIsGfztyq1BNzCGx94sQ'; img-src 'self' data:; report-uri /csp-report/
Content-Security-Policy-Report-Only: default-src 'none'; script-src 'self' 'nonce-hvEIsGfztyq1BNzCGx94sQ' 'report-sample'; style-src 'self' 'nonce-hvEIsGfztyq1BNzCGx94sQ'; img-src 'self'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'; report-uri /csp-report/

We open the page in Chrome and click the button. The image is shown, because the enforced policy allows it, and the browser only reports the violation of the report-only policy. The click does nothing: the handler violates the enforced policy and is blocked. The browser sends a report for each violation of each policy.

The page with the data image and the blocked button
Figure: The image is allowed, the button handler is blocked

The demo script prints the stored reports. The field disposition tells which policy was violated: enforce for the enforced one and report for the report-only one. The effective directive script-src-attr is the part of script-src that covers event handler attributes, and the sample shows the blocked code.

demos/reports.py
import os

import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()

from pages.models import ViolationReport

for report in ViolationReport.objects.order_by('disposition', 'directive'):
    print(f'{report.disposition:8} {report.directive:16} {report.blocked_uri[:40]:42} {report.sample[:30]!r}')

In production the reports show which pages would break under the stricter policy, as well as injected scripts and browser extensions. The last command checks that the view rejects a body that is not a report.

$ uv run python -m demos.reports
enforce  script-src-attr  inline                                     "this.textContent = 'clicked'"
report   img-src          data                                       ''
report   script-src-attr  inline                                     "this.textContent = 'clicked'"
$ curl -s -i -X POST -d 'nonsense' localhost:8000/csp-report/ | head -n 1
HTTP/1.1 400 Bad Request

Policies for single views

Some pages need a different policy. The decorator csp_override() replaces the enforced policy of a view with its own dictionary, and csp_report_only_override() does the same for the report-only policy; an empty dictionary removes the header. The view video embeds a player from another site, so it allows frames from that host; the view legacy is an old page with inline handlers that is excluded until it is rewritten.

pages/views.py
import json

from django.http import HttpResponse, HttpResponseBadRequest
from django.shortcuts import render
from django.utils.csp import CSP
from django.views.decorators.csp import csp_override, csp_report_only_override
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST

from .models import ViolationReport


def home(request):
    return render(request, 'pages/home.html')


def status(request):
    return HttpResponse('ok', content_type='text/plain')


@csp_override({
    'default-src': [CSP.SELF],
    'frame-src': ['https://www.youtube-nocookie.com'],
})
def video(request):
    return HttpResponse('<iframe src="https://www.youtube-nocookie.com/embed/x"></iframe>')


@csp_override({})
@csp_report_only_override({})
def legacy(request):
    return HttpResponse('<p onclick="alert(1)">an old page with inline handlers</p>')


@csrf_exempt
@require_POST
def csp_report(request):
    try:
        report = json.loads(request.body)['csp-report']
    except (ValueError, KeyError, TypeError):
        return HttpResponseBadRequest('invalid report')

    ViolationReport.objects.create(
        disposition=report.get('disposition', '')[:10],
        directive=report.get('effective-directive', '')[:40],
        blocked_uri=report.get('blocked-uri', '')[:200],
        document_uri=report.get('document-uri', '')[:200],
        sample=report.get('script-sample', '')[:100],
    )
    return HttpResponse(status=204)

The two views get their paths.

pages/urls.py
from django.urls import path

from . import views

urlpatterns = [
    path('', views.home, name='home'),
    path('status/', views.status, name='status'),
    path('video/', views.video, name='video'),
    path('legacy/', views.legacy, name='legacy'),
    path('csp-report/', views.csp_report, name='csp_report'),
]

The demo script prints the headers of the views. The overriding dictionary is used as it is, not merged with SECURE_CSP, so it must repeat the directives it wants to keep.

demos/overrides.py
import os

import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()

from django.test import Client
from django.test.utils import setup_test_environment

setup_test_environment()

client = Client()
for path in ['/status/', '/video/', '/legacy/']:
    response = client.get(path)
    print(path)
    print('  enforced:   ', response.get('Content-Security-Policy', '-'))
    print('  report-only:', response.get('Content-Security-Policy-Report-Only', '-')[:60])

The plain view has the global policies, the video view its own enforced policy and the global report-only policy, and the legacy view none.

$ uv run python -m demos.overrides
/status/
  enforced:    default-src 'self'; script-src 'self' 'report-sample'; style-src 'self'; img-src 'self' data:; report-uri /csp-report/
  report-only: default-src 'none'; script-src 'self' 'report-sample'; style
/video/
  enforced:    default-src 'self'; frame-src https://www.youtube-nocookie.com
  report-only: default-src 'none'; script-src 'self' 'report-sample'; style
/legacy/
  enforced:    -
  report-only: -

Testing the policy

Tests check the headers, the nonces, and the overrides. override_settings() changes the policy for a test, which the middleware reads for each response. The report view is tested with a JSON body in the content type application/csp-report, which browsers use.

pages/tests.py
import json
import re

from django.test import TestCase, override_settings

from .models import ViolationReport


class CspTests(TestCase):

    def test_policy_header(self):
        response = self.client.get('/')
        policy = response['Content-Security-Policy']
        self.assertIn("default-src 'self'", policy)
        self.assertIn('Content-Security-Policy-Report-Only', response.headers)

    def test_nonce_in_header_and_page(self):
        response = self.client.get('/')
        nonce = re.search(r"'nonce-([^']+)'", response['Content-Security-Policy'])[1]
        self.assertContains(response, f'nonce="{nonce}"', count=2)

    def test_nonce_changes(self):
        first = self.client.get('/')['Content-Security-Policy']
        second = self.client.get('/')['Content-Security-Policy']
        self.assertNotEqual(first, second)

    def test_override_removes_policy(self):
        response = self.client.get('/legacy/')
        self.assertNotIn('Content-Security-Policy', response.headers)

    @override_settings(SECURE_CSP={})
    def test_no_policy_without_setting(self):
        response = self.client.get('/')
        self.assertNotIn('Content-Security-Policy', response.headers)

    def test_report_is_stored(self):
        report = {'csp-report': {'disposition': 'enforce', 'effective-directive': 'img-src',
                                 'blocked-uri': 'https://evil.example/x.png',
                                 'document-uri': 'http://testserver/'}}
        response = self.client.post('/csp-report/', json.dumps(report), content_type='application/csp-report')
        self.assertEqual(response.status_code, 204)
        self.assertEqual(ViolationReport.objects.get().directive, 'img-src')

All six tests pass.

$ uv run python manage.py test 2>&1
Found 6 test(s).
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
......
----------------------------------------------------------------------
Ran 6 tests in 0.007s

OK
Destroying test database for alias 'default'...

Source

Django documentation: Content Security Policy

Django documentation: How to use Django’s Content Security Policy

MDN: Content Security Policy (CSP)

In this article we have used the built-in CSP support of Django: we added a policy with SECURE_CSP and watched the browser block inline code, allowed inline elements with nonces, tested a stricter policy in report-only mode, collected violation reports, changed the policy for single views, and tested the headers. Related articles are Django middleware, Django templates, and Django settings and environment.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Django tutorials.