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
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