[Answered ]-Django, CSP: How to activate Nonce in scripts for Admin pages

1👍

Ok I could also add all script hashes to CSP, that is also working. But maybe there is also another solution?

👤TomK

0👍

Here’s a quickie I just figured out that may help you. It doesn’t fix the root problem in the original which is resources missing a nonce, but you can add a second reference to the resource that includes the nonce (assumes all your CSP setup is working). Given the example below of calendar.js, it’ll be referenced in the HTML twice. The first will generate the CSP error, but the second will work. Your console will be a bit messy but all your nonce’d stuff will work again.

  1. In your base templates directory, add another directory called admin
  2. There, create a file called base.html, i.e. templates/admin/base.html. It is in here you’ll add additional stuff.

That’s it.

The additional stuff inside your local templates/admin/base.html:

{% extends "admin/base.html" %}
{% load static %}

{% block extrastyle %}
<script nonce="{{request.csp_nonce}}" src="/static/admin/js/calendar.js"></script>

<!-- whatever else you need with a nonce -->

{% endblock %}

Leave a comment