Skip to main content

Nonce support for Content Security Policy in Django.

Project description

Build Status

DCN is a Content-Security-Policy nonce injection support system for Django and CSP.

It provides for on-the-fly nonce creation and deployment. Once installed, DCN will generate a unique nonce
for each request (one for script-src and a separate one for style-src directives) append the nonce to the
CSP header, then make the nonce(s) accessible to the templates via the Django Context Processors.
DCN stays out of the way of Django-CSP and can operate
independently with any method of CSP insertion that passes through Django Middleware.


  • This code has not been through a third party security audit.
  • I’ve successfully tested this locally with pypy-5.4.1. TravisCI has confirmed this doesn’t work with their version.


pip install django-csp-nonce


    [ ... ]
    # Make sure you put it *above* django-csp if you're using it
    [ ... ]

Add DCN to context_processors:

        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [...],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                [ ... ]

Finally, add DCN directives to settings:

CSP_NONCE_SCRIPT = False  # True if you want to use it
CSP_NONCE_STYLE = False  # True if you want to use it
CSP_FLAG_STRICT = False  # True to include strict-dynamic in CSP


DCN takes care of nonce generation for you. As you work on your templates, pull in your specific nonce from the context:

<script type="text/javascript" {{ script_nonce }}>

<style {{ style_nonce }}>


  • Django

Known issues

  • Nonce sync breaks on settings.DEBUG=True

Important Changes

  • 1.0
    • Out of beta!
    • PyNacl is no longer a dependency. (Moving forward the aim is to stay compatible with environments such as Google App Engine which don’t support non-python extensions.)

Running Tests

Use tox to run the tests against multiple versions of Python that you have installed and multiple versions of Django. Please make sure that you run your tests against at least Python 2.7 and Python 3.5.

virtualenv venv
. ./venv/bin/activate

pip install tox


Project details

Release history Release notifications

This version


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for django-csp-nonce, version 1.0.0
Filename, size File type Python version Upload date Hashes
Filename, size django_csp_nonce-1.0.0-py2.py3-none-any.whl (11.5 kB) File type Wheel Python version py2.py3 Upload date Hashes View hashes

Supported by

Elastic Elastic Search Pingdom Pingdom Monitoring Google Google BigQuery Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN SignalFx SignalFx Supporter DigiCert DigiCert EV certificate StatusPage StatusPage Status page