Django 6.1.3

4.7 HTTP, routing, and views

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 and its 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 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:

  1. It decorates itself with @csp_override({}) and @csp_report_only_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 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. 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 so the debug template’s automatic callable resolution does not accidentally execute your setting while displaying it!
  1. POST parameters via @sensitive_post_parameters: Decorating a view with sensitive_post_parameters("api_token") 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).
  2. Local frame variables via @sensitive_variables: On synchronous functions, 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:

Recorded on Django 6.1.3 ch04-routing script
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!

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.

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 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

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.