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

# Debug pages and response lifecycle

How does `ExceptionReporter` scrub sensitive variables for 500 error reports, and what closes a response after the view returns?

Every unhandled exception that hits Chapter 3's `handle_uncaught_exception` with `settings.DEBUG = True` (or gets mailed to `"ADMINS"` by `AdminEmailHandler` in production) flows through **`ExceptionReporter`** (`django/views/debug.py:ExceptionReporter`) and its **`SafeExceptionReporterFilter`** (`django/views/debug.py:SafeExceptionReporterFilter`) — Django's **sensitive filter**.

## Standalone rendering and content negotiation

Look at the very top of `django/views/debug.py` (lines 28–31). Django constructs a private module-level `DEBUG_ENGINE = Engine(debug=True, libraries={"i18n": "django.templatetags.i18n"})` completely independent of `settings.TEMPLATES`. It reads `"technical_500.html"` and `"technical_500.txt"` straight from disk via `builtin_template_path` (`django/views/debug.py:builtin_template_path`) so Django can still render an error page even when your project's template backend or loaders are the exact thing that crashed.

Now look at `technical_500_response` (`django/views/debug.py:technical_500_response`):

1. It decorates itself with `@csp_override({})` and `@csp_report_only_override({})` (`django/views/decorators/csp.py:csp_override`) so strict Content-Security-Policy headers in Django `6.1` do not block the inline styles and toggle scripts on Django's yellow-and-grey traceback page!
2. It performs HTTP content negotiation via `HttpRequest.get_preferred_type` (`django/http/request.py:HttpRequest.get_preferred_type`) against `["text/html", "text/plain"]`: browsers sending `"Accept: text/html"` receive `ExceptionReporter.get_traceback_html`, while API clients or curl sending `"Accept: text/plain"` receive the concise plain-text `ExceptionReporter.get_traceback_text`!

## How `SafeExceptionReporterFilter` scrubs secrets — and when it turns off

Open `SafeExceptionReporterFilter` (`django/views/debug.py:SafeExceptionReporterFilter`). It protects three distinct surfaces:

1. **Settings, `META`, and cookies:** `SafeExceptionReporterFilter.hidden_settings` compiles the case-insensitive pattern `"API|AUTH|TOKEN|KEY|SECRET|PASS|SIGNATURE|HTTP_COOKIE"` — plus whatever `settings.SESSION_COOKIE_NAME` is configured to (`"sessionid"` by default). `SafeExceptionReporterFilter.cleanse_setting` walks nested dictionaries, lists, and tuples recursively, replacing any matching value with `cleansed_substitute` (`"********************"`, twenty asterisks). Any callable sitting inside `settings` is wrapped in `CallableSettingWrapper` (`django/views/debug.py:CallableSettingWrapper`) so the debug template's automatic callable resolution does not accidentally *execute* your setting while displaying it!

> **History.** `CallableSettingWrapper` carries two ticket comments right in its docstring (lines 48–54 of `django/views/debug.py`): `#21345` (because Django's template variable resolver automatically calls any zero-argument callable during rendering, displaying `settings` used to accidentally invoke callable settings on the 500 page!) and `#23070` (protecting against callables that reject attribute assignment like `do_not_call_in_templates = True`).

2. **POST parameters via `@sensitive_post_parameters`:** Decorating a view with `sensitive_post_parameters("api_token")` (`django/views/decorators/debug.py:sensitive_post_parameters`) attaches `sensitive_post_parameters = ("api_token",)` (or `"__ALL__"` with no arguments) onto `HttpRequest` at request time. When an exception occurs, `SafeExceptionReporterFilter.get_post_parameters` replaces those keys with twenty asterisks — and `get_cleansed_multivaluedict` also scrubs `MultiValueDict` instances inside local traceback frames so a `KeyError` on `request.POST["missing"]` does not leak `"password"` in the traceback locals (`#21098`).
3. **Local frame variables via `@sensitive_variables`:** On synchronous functions, `sensitive_variables` (`django/views/decorators/debug.py:sensitive_variables`) stores variable names on the wrapper function; on `async def` functions, because coroutine frames do not expose wrapper function attributes the same way, lines 58–64 hash `f"{file_path}:{first_line_number}"` into the module-level dictionary `coroutine_functions_to_sensitive_variables`!

Now test `SafeExceptionReporterFilter` under `DEBUG = False` versus `DEBUG = True` live on Django `6.1.3`:

```text recording=ch04-routing
ExceptionReporter, SafeExceptionReporterFilter, and technical_500_response negotiation
  get_safe_settings(): SECRET_KEY='********************' LANGUAGE_CODE='en-us'
  DEBUG=False is_active=True  get_post_parameters={'headline': ['Mayor speaks'], 'api_token': ['********************']}
  DEBUG=True  is_active=False get_post_parameters={'headline': ['Mayor speaks'], 'api_token': ['sk-live-99999']}
  technical_500_response Accept='text/html' -> status=500 Content-Type='text/html' is_html=True contains_exc=True
  technical_500_response Accept='text/plain' -> status=500 Content-Type='text/plain; charset=utf-8' is_html=False contains_exc=True
```

LOOK AT LINES 2 AND 3 OF THAT TRACE — a deliberate design choice that regularly surprises developers testing their scrubbing decorators locally!

- `SafeExceptionReporterFilter.get_safe_settings` **always** scrubs `SECRET_KEY` (even when `DEBUG = True`).
- By contrast, `SafeExceptionReporterFilter.get_post_parameters` and `get_traceback_frame_variables` check `SafeExceptionReporterFilter.is_active(request)` (`django/views/debug.py:SafeExceptionReporterFilter.is_active`): **`return settings.DEBUG is False`**. When `DEBUG = True`, `@sensitive_post_parameters` and `@sensitive_variables` intentionally deactivate (`is_active=False`), leaving `"api_token": ["sk-live-99999"]` visible on your local browser debug page and turning scrubbing on only when `DEBUG = False` (for production `AdminEmailHandler` reports and error collectors)!

## Closing the response and cleaning up resources

Whether a request produced a `200` `TemplateResponse`, a `StreamingHttpResponse`, or a `500` error page, every request finishes at one chokepoint: `HttpResponseBase.close` (`django/http/response.py:HttpResponseBase.close`).

```python
def close(self):
    for closer in self._resource_closers:
        try:
            closer()
        except Exception:
            pass
    self._resource_closers.clear()
    self.closed = True
    signals.request_finished.send(sender=self._handler_class)
```

Trace every closer registered on `_resource_closers` across a request's life:

1. `BaseHandler.get_response` and `BaseHandler.get_response_async` append `HttpRequest.close` (`django/http/request.py:HttpRequest.close`) to `_resource_closers` right after `_middleware_chain` returns. `HttpRequest.close` iterates every uploaded file in `_files` and closes its open handle (deleting `TemporaryUploadedFile` temp files on disk!).
2. `StreamingHttpResponse._set_streaming_content` appends the streaming iterator's `"close"` method if present, and `FileResponse._set_streaming_content` appends the open file handle's `"close"` method.
3. On WSGI, the server calls `HttpResponseBase.close` after iterating the response bytes (or via the monkey-patched `"file_to_stream.close"` for `"wsgi.file_wrapper"`). On ASGI, `ASGIHandler.handle` calls `await sync_to_async(response.close)()` after `send_response` completes.
4. Finally, `request_finished` fires — triggering `reset_urlconf` (clearing the thread/task URLconf override) and `django.db.close_old_connections` (closing expired or broken database sockets so the next request starts clean).

## Where debug pages and teardown leak

- **Testing `@sensitive_post_parameters` with `DEBUG = True` looks broken.** Because `SafeExceptionReporterFilter.is_active` returns `False` whenever `DEBUG = True`, developers frequently think their `@sensitive_post_parameters` decorator failed to apply. Test scrubbing with `@override_settings(DEBUG=False)` (or subclass `SafeExceptionReporterFilter` and override `is_active` if you want scrubbing even in staging `DEBUG = True`).
- **Custom secret names that dodge `hidden_settings` leak in error reports.** A setting named `"STRIPE_CREDENTIALS"` or `"BILLING_DSN"` contains none of `API|AUTH|TOKEN|KEY|SECRET|PASS|SIGNATURE|HTTP_COOKIE`, so `SafeExceptionReporterFilter.cleanse_setting` displays it in plaintext unless you rename it (e.g. `"STRIPE_API_KEY"`) or override `DEFAULT_EXCEPTION_REPORTER_FILTER`.
- **`HttpResponseBase.close` swallows closer exceptions silently.** Notice lines 339–342 of `django/http/response.py`: any exception inside a custom generator's `"close()"` method is caught and ignored so `request_finished` is still guaranteed to fire.

We have now walked a request all the way from WSGI/ASGI entry through the middleware onion, HTTP parsing, URL compilation, decorators, CBVs, error scrubbing, and teardown. Before leaving Part I for the ORM, one major pillar of the request stack still deserves its own dedicated microscope: how Django's built-in security middleware shields every endpoint by default — and the exact edges where configuration defeats it — in [Security by default](../security.md).
