Django 6.1.3

5.5 Security by default

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/middleware/clickjacking.py — the entire middleware is 48 lines. On the response path (XFrameOptionsMiddleware.process_response, lines 25–38), it checks only two escape hatches before writing the header:

  1. If "X-Frame-Options" is already present via HttpResponseBase.get, it leaves the existing header untouched.
  2. If getattr(response, "xframe_options_exempt", False) is True (set by @xframe_options_exempt, xframe_options_exempt), it returns without adding any header.
  3. 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.iscoroutinefunction 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/utils/safestring.py 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!

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:

Recorded on Django 6.1.3 ch05-security script
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='&lt;b&gt;&lt;script&gt;alert(1)&lt;/script&gt;'
  mark_safe('<b>%s</b>') % str -> type=str        safe=False rendered='&lt;b&gt;&lt;script&gt;alert(1)&lt;/script&gt;&lt;/b&gt;'
  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>&lt;script&gt;alert(1)&lt;/script&gt;</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:

  1. mark_safe(f"<b>{x}</b>") is a live XSS vulnerability. Python evaluates the f-string before mark_safe is ever called. mark_safe sees one plain string "<b><script>alert(1)</script></b>", wraps it blindly in SafeString, and tells the template engine: “trust every byte of this; do not escape it.”
  2. format_html("<b>{}</b>", x) escapes every argument before formatting and marking safe:
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))
  1. Look at lines 141–142 in Django 6.1: developers (and LLMs!) used to write format_html(f"<b>{x}</b>") thinking the function name alone made HTML safe — passing a pre-interpolated f-string with zero args or kwargs, which silently turned format_html into mark_safe! After deprecating zero-argument calls in Django 5.0, Django 6.0/6.1 now raises TypeError: 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/json">, 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

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.