---
django: 6.1.3 (f16e25dcb9fe55734ba4ea2b00ac34405b7df74a)
---

# 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` (`django/middleware/clickjacking.py:XFrameOptionsMiddleware`), and blocks the second with automatic HTML escaping built around **`SafeString`** (`django/utils/safestring.py:SafeString`), **`mark_safe`** (`django/utils/safestring.py:mark_safe`), and **`format_html`** (`django/utils/html.py: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` (`django/http/response.py:HttpResponseBase.get`), it leaves the existing header untouched.
2. If `getattr(response, "xframe_options_exempt", False)` is `True` (set by `@xframe_options_exempt`, `django/views/decorators/clickjacking.py: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` (`django/views/decorators/clickjacking.py: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`, `django/utils/html.py:conditional_escape`) rests on a single duck-typed protocol: **`hasattr(text, "__html__")`**.

Open `django/utils/safestring.py` lines 13–52:

```python
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 `SafeString` subclasses `str` with `__slots__ = ()`, it adds zero per-instance `__dict__` overhead and behaves like an ordinary Python string everywhere.
- `SafeString.__add__` preserves the `SafeString` type **only when BOTH operands are `SafeData`** (`mark_safe("<b>") + mark_safe("ok</b>")`). The instant you concatenate a `SafeString` with a plain untrusted `str` (`mark_safe("<b>") + payload`), `super().__add__(rhs)` returns a plain `str` — intentionally **stripping safety** so the template engine will autoescape the whole result!
- Even more importantly, `SafeString` does **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-in `str` and returns a plain `str`, stripping the safe flag by design so you can never accidentally smuggle unescaped data into a `SafeString` via `"%s"` or `str.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`:

```text recording=ch05-security
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)` (`django/utils/html.py:format_html`) escapes every argument *before* formatting and marking safe:**

```python
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))
```

3. **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` (`django/utils/html.py: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` (`django/utils/html.py: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:alert(1)"` URLs, or raw interpolation inside `<script>` or `<style>` blocks! Validate URL schemes explicitly (`url_has_allowed_host_and_scheme` or `django.forms.URLField`) and pass data to JavaScript through `django.utils.html.json_script`, never template interpolation.
- **`|safe` in templates is identical to `mark_safe`.** Passing user-authored Markdown or CMS HTML through `|safe` without an allow-list HTML sanitizer (such as nh3) opens stored XSS immediately.
- **Plain `str.join` on a list of `SafeString` items strips safety.** `"".join([mark_safe("<li>a</li>"), mark_safe("<li>b</li>")])` returns a plain `str` (causing the template to render literal `&lt;li&gt;`), which tempts people into wrapping the result in `mark_safe(...)` — where one unescaped item in the list becomes XSS. Use `format_html_join` instead.

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](where-defaults-stop.md).
