Personal Catalogue: Django & PostgreSQL — Chapter 5, Exercise 2
====================================================
TASK
Explain what json_script actually produces in the rendered HTML, and
why it's genuinely safer than building the equivalent
The type="application/json" attribute is deliberate - it tells the
browser this script block is data, not executable JavaScript, so
nothing inside it ever runs directly. The JavaScript that later reads
this data does so explicitly, via
JSON.parse(document.getElementById('creator-labels-data').textContent).
WHAT A HAND-BUILT ALTERNATIVE WOULD LOOK LIKE
Without json_script, achieving the same result by hand might look like:
where creator_labels_json is a JSON string built in the view and marked
safe so Django's own automatic HTML-escaping doesn't interfere with it.
WHY THIS HAND-BUILT VERSION IS GENUINELY LESS SAFE
Marking a value safe tells Django to skip its own automatic escaping
entirely for that value, trusting the developer to have already made it
safe. If any part of the underlying data ever contained
attacker-influenced content - a tag name coming from user input,
for example - and that content contained something like or
other HTML-breaking characters, marking the whole blob safe would let
that content break out of the intended script tag and inject real,
executable content into the page, a genuine cross-site-scripting risk.
json_script avoids this problem structurally: it always correctly
escapes the JSON content for safe inclusion inside an HTML script tag,
regardless of what the underlying Python data contains, without
requiring a developer to remember to mark anything safe or verify the
data is trustworthy first.
ANSWER: json_script renders a real