Framing rules and safe strings
How does XFrameOptionsMiddleware guard responses against clickjacking, and how does SafeString propagate through Python string operations without losing its escape flag?
Two of the oldest web attacks exploit what the browser renders rather than what the server computes: clickjacking (layering your page inside a transparent <iframe> so a user clicking a fake button actually clicks “Publish” on your newsroom desk) and cross-site scripting (XSS) (injecting unescaped <script> or attribute payloads into HTML output).
Django blocks the first with XFrameOptionsMiddleware, and blocks the second with automatic HTML escaping built around SafeString, mark_safe, and format_html.
XFrameOptionsMiddleware and its three view decorators
Open django/ — the entire middleware is 48 lines. On the response path (XFrameOptionsMiddleware, lines 25–38), it checks only two escape hatches before writing the header:
- If
"X-Frame-Options"is already present viaHttpResponseBase, it leaves the existing header untouched..get - If
getattr(response, "xframe_options_exempt", False)isTrue(set by@xframe_options_exempt,xframe_options_exempt), it returns without adding any header. - Otherwise, it stamps
response..headers["X-Frame-Options"] = getattr(settings, "X_FRAME_OPTIONS", "DENY").upper()
Since Django 3.0, the default setting is "DENY" (not "SAMEORIGIN"), blocking framing even from your own origin unless a view explicitly opts in with @xframe_options_sameorigin or sets a CSP frame-ancestors directive (which modern browsers prefer over X-Frame-Options when both are present).
Notice also how the three clickjacking decorators (xframe_options_deny, xframe_options_sameorigin, xframe_options_exempt) work on both def and async def views by branching on inspect and attaching the header or attribute to the returned HttpResponse — adding just +6.0 us per request (85.2 -> 91.2 us in ch05-bench).
How SafeString propagates — and when Python strips the flag
Autoescaping in Django’s template engine (and inside conditional_escape, conditional_escape) rests on a single duck-typed protocol: hasattr(text, "__html__").
Open django/ lines 13–52:
class SafeData:
__slots__ = ()
def __html__(self):
return self
class SafeString(str, SafeData):
__slots__ = ()
def __add__(self, rhs):
if isinstance(rhs, str):
t = super().__add__(rhs)
if isinstance(rhs, SafeData):
t = SafeString(t)
return t
return NotImplemented
Look closely at what SafeString overrides — and what it deliberately does not override!
- Because
SafeStringsubclassesstrwith__slots__ = (), it adds zero per-instance__dict__overhead and behaves like an ordinary Python string everywhere. SafeStringpreserves the.__add__ SafeStringtype only when BOTH operands areSafeData(mark_safe("<b>") + mark_safe("ok</). The instant you concatenate ab>") SafeStringwith a plain untrustedstr(mark_safe("<b>") + payload),super().__add__(rhs)returns a plainstr— intentionally stripping safety so the template engine will autoescape the whole result!- Even more importantly,
SafeStringdoes not override__mod__(%),str.format,str.join,str.replace, or slicing ([a:b]). Every one of those methods is inherited straight from Python’s built-instrand returns a plainstr, stripping the safe flag by design so you can never accidentally smuggle unescaped data into aSafeStringvia"%s"orstr.format.
Why mark_safe is a scalpel and format_html is the safe default
Now watch every single combination run live through Django’s template engine on Django 6.1.3:
XFrameOptionsMiddleware, SafeString propagation, mark_safe, and format_html
X-Frame-Options: default='DENY' @sameorigin='SAMEORIGIN' @exempt=None
mark_safe + mark_safe -> type=SafeString safe=True rendered='<b>ok</b>'
mark_safe + untrusted str -> type=str safe=False rendered='<b><script>alert(1)</script>'
mark_safe('<b>%s</b>') % str -> type=str safe=False rendered='<b><script>alert(1)</script></b>'
mark_safe(f'<b>{x}</b>') -> type=SafeString safe=True rendered='<b><script>alert(1)</script></b>' <-- XSS!
format_html('<b>{}</b>', x) -> type=SafeString safe=True rendered='<b><script>alert(1)</script></b>'
Django 6.1 format_html(f'...') with 0 args -> TypeError: args or kwargs must be provided.
Compare lines 47, 48, and 49 — those three lines explain the #1 XSS mistake in real Django codebases:
mark_safe(f"<b>{x}</is a live XSS vulnerability. Python evaluates the f-string beforeb>") mark_safeis ever called.mark_safesees one plain string"<b><script>alert(1)</, wraps it blindly inscript></ b>" SafeString, and tells the template engine: “trust every byte of this; do not escape it.”format_html("<b>{}</escapes every argument before formatting and marking safe:b>", x)
def format_html(format_string, *args, **kwargs):
if not (args or kwargs):
raise TypeError("args or kwargs must be provided.")
args_safe = map(conditional_escape, args)
kwargs_safe = {k: conditional_escape(v) for (k, v) in kwargs.items()}
return mark_safe(format_string.format(*args_safe, **kwargs_safe))
- Look at lines 141–142 in Django
6.1: developers (and LLMs!) used to writeformat_html(f"<b>{x}</thinking the function name alone made HTML safe — passing a pre-interpolated f-string with zerob>") argsorkwargs, which silently turnedformat_htmlintomark_safe! After deprecating zero-argument calls in Django5.0, Django6.0/6.1now raisesTypeError: args or kwargs must be provided.immediately, turning a silent XSS vulnerability into a loud crash at development time.
For joining sequences of fragments, use format_html_join, which runs conditional_escape on the separator as well as every tuple/mapping of arguments; for embedding Python values inside <script type="application/, use json_script, which translates <, >, and & to \u003C, \u003E, and \u0026 so user text containing "</script>" cannot break out of the script tag.
Where framing and escaping shields leak
- HTML escaping does not make every HTML context safe. Escaping
<,>,",', and&protects HTML text nodes and quoted attributes (<a title="{{ x }}">). It does not protect unquoted attributes (<div class={{ x }}>),href="{{ url }}"with"javascript:URLs, or raw interpolation insidealert(1)" <script>or<style>blocks! Validate URL schemes explicitly (url_has_allowed_host_and_schemeordjango) and pass data to JavaScript through.forms .URLField django, never template interpolation..utils .html .json_script |safein templates is identical tomark_safe. Passing user-authored Markdown or CMS HTML through|safewithout an allow-list HTML sanitizer (such as nh3) opens stored XSS immediately.- Plain
str.joinon a list ofSafeStringitems strips safety."".join([mark_safe("<li>a</returns a plainli>"), mark_safe("<li>b</ li>")]) str(causing the template to render literal<li>), which tempts people into wrapping the result inmark_safe(...)— where one unescaped item in the list becomes XSS. Useformat_html_joininstead.
We have now opened every single built-in security mechanism in Django’s default stack. The final section of Part I draws the hard line between what those mechanisms guarantee and what remains entirely your responsibility: Where Django’s defaults stop protecting you.