Skip to main content
  1. My Blog Posts and Stories/

Reviving the Content Security Policy (CSP) on Django

··241 words·2 mins

Now how do I revive the Content Security Policy (CSP) for Django?

When I was doing it in flask, there was a build in library for doing so. In that case, is there a built in one for Django as well?

I went on a journey to find out what is the Django equivalent version of building CSP for Flask. I stumbled upon this library django-csp. This library is even maintained by Mozilla, our friendly neighborhood firefox developer.

How do you install it? #

  1. Install it using pip install django-csp

How do we use it? #

  1. Add the default directives that we want into
  2. Add decorators to have special directives for special pages.
  3. Profit??

There are a lot of directives which are available within the documentation but I will just be going through some of the more prominent ones which I used. All the directives are assigned within the python.

An example will be a code snippet here:

CSP_DEFAULT_SRC = ("'none'",) # Sets Default-src to 'none'

Here are some of the directives which I used

  1. CSP_STYLE_SRC to restrict the CSS files that can be imported
  2. CSP_SCRIPT_SRC to restrict the JavaScript files that can be imported
  3. CSP_REPORT_TO to report CSP violations
  4. CSP_FORM_ACTION to restrict the form submissions

I might have mentioned it before but cspscanner is very useful when it comes to testing if the CSP policy is secure. With that, my CSP is once again mighty XD.

CSP A+ Grade
A+ CSP Grade