{# Page assets live INSIDE the content block (the dj-root): dj-navigate swaps only that region, so anything in extra_head/extra_scripts is missing when a visitor arrives by live navigation. Behaviour lives in static/js/site-pages.js. #}
DJE-003 Error Security

Using escape() instead of json.dumps() for JavaScript contexts

Error message

JavaScript syntax error or XSS from improperly escaped content

Django's escape() function only handles HTML entities (&, <, >, ", '). It does not escape backslashes, newlines, or other characters that are significant in JavaScript string contexts. This can lead to XSS or syntax errors when embedding dynamic values in <script> tags or JS event handlers.

javascript security xss

Affected versions: >=0.2.0

Solution

Recommended

Use json.dumps() for JavaScript string values

json.dumps() properly escapes all special characters for JavaScript contexts, including backslashes, newlines, quotes, and Unicode characters.

Before (problematic)
from django.utils.html import escape

context["js_name"] = escape(user_input)
# Template: <script>var name = "{{ js_name }}";</script>
After (fixed)
import json

context["js_name"] = json.dumps(user_input)
# Template: <script>var name = {{ js_name }};</script>
# json.dumps adds the quotes automatically