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 (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/ (lines 28–31). Django constructs a private module-level DEBUG_ENGINE = Engine(debug=True, libraries={"i18n": "django completely independent of settings. It reads "technical_500 and "technical_500 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:
- It decorates itself with
@csp_override({})and@csp_report_only_override({})so strict Content-Security-Policy headers in Django6.1do not block the inline styles and toggle scripts on Django’s yellow-and-grey traceback page! - It performs HTTP content negotiation via
HttpRequestagainst.get_preferred_type ["text/: browsers sendinghtml", "text/ plain"] "Accept: text/receivehtml" ExceptionReporter, while API clients or curl sending.get_traceback_html "Accept: text/receive the concise plain-textplain" ExceptionReporter!.get_traceback_text
How SafeExceptionReporterFilter scrubs secrets — and when it turns off
Open SafeExceptionReporterFilter. It protects three distinct surfaces:
- Settings,
META, and cookies:SafeExceptionReporterFiltercompiles the case-insensitive pattern.hidden_settings "API|AUTH|TOKEN|KEY|SECRET|PASS|SIGNATURE|HTTP_COOKIE"— plus whateversettingsis configured to (.SESSION_COOKIE_NAME "sessionid"by default).SafeExceptionReporterFilterwalks nested dictionaries, lists, and tuples recursively, replacing any matching value with.cleanse_setting cleansed_substitute("********************", twenty asterisks). Any callable sitting insidesettingsis wrapped inCallableSettingWrapperso the debug template’s automatic callable resolution does not accidentally execute your setting while displaying it!
- POST parameters via
@sensitive_post_parameters: Decorating a view withsensitive_post_parameters("api_token")attachessensitive_post_parameters = ("api_token",)(or"__ALL__"with no arguments) ontoHttpRequestat request time. When an exception occurs,SafeExceptionReporterFilterreplaces those keys with twenty asterisks — and.get_post_parameters get_cleansed_multivaluedictalso scrubsMultiValueDictinstances inside local traceback frames so aKeyErroronrequestdoes not leak.POST["missing"] "password"in the traceback locals (#21098). - Local frame variables via
@sensitive_variables: On synchronous functions,sensitive_variablesstores variable names on the wrapper function; onasync deffunctions, because coroutine frames do not expose wrapper function attributes the same way, lines 58–64 hashf"{file_path}:into the module-level dictionary{first_line_number}" coroutine_functions_to_sensitive_variables!
Now test SafeExceptionReporterFilter under DEBUG = False versus DEBUG = True live on Django 6.1.3:
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!
SafeExceptionReporterFilteralways scrubs.get_safe_settings SECRET_KEY(even whenDEBUG = True).- By contrast,
SafeExceptionReporterFilterand.get_post_parameters get_traceback_frame_variablescheckSafeExceptionReporterFilter:.is_active(request) return settings. When.DEBUG is False DEBUG = True,@sensitive_post_parametersand@sensitive_variablesintentionally deactivate (is_active=False), leaving"api_token": ["sk-live-99999"]visible on your local browser debug page and turning scrubbing on only whenDEBUG = False(for productionAdminEmailHandlerreports 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.
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:
BaseHandlerand.get_response BaseHandlerappend.get_response_async HttpRequestto.close _resource_closersright after_middleware_chainreturns.HttpRequestiterates every uploaded file in.close _filesand closes its open handle (deletingTemporaryUploadedFiletemp files on disk!).StreamingHttpResponseappends the streaming iterator’s._set_streaming_content "close"method if present, andFileResponseappends the open file handle’s._set_streaming_content "close"method.- On WSGI, the server calls
HttpResponseBaseafter iterating the response bytes (or via the monkey-patched.close "file_to_streamfor.close" "wsgi). On ASGI,.file_wrapper" ASGIHandlercalls.handle await sync_to_async(responseafter.close)() send_responsecompletes. - Finally,
request_finishedfires — triggeringreset_urlconf(clearing the thread/task URLconf override) anddjango(closing expired or broken database sockets so the next request starts clean)..db .close_old_connections
Where debug pages and teardown leak
- Testing
@sensitive_post_parameterswithDEBUG = Truelooks broken. BecauseSafeExceptionReporterFilterreturns.is_active FalsewheneverDEBUG = True, developers frequently think their@sensitive_post_parametersdecorator failed to apply. Test scrubbing with@override_settings(DEBUG=False)(or subclassSafeExceptionReporterFilterand overrideis_activeif you want scrubbing even in stagingDEBUG = True). - Custom secret names that dodge
hidden_settingsleak in error reports. A setting named"STRIPE_CREDENTIALS"or"BILLING_DSN"contains none ofAPI|AUTH|TOKEN|KEY|SECRET|PASS|SIGNATURE|HTTP_COOKIE, soSafeExceptionReporterFilterdisplays it in plaintext unless you rename it (e.g..cleanse_setting "STRIPE_API_KEY") or overrideDEFAULT_EXCEPTION_REPORTER_FILTER. HttpResponseBaseswallows closer exceptions silently. Notice lines 339–342 of.close django/: any exception inside a custom generator’shttp/ response .py "close()"method is caught and ignored sorequest_finishedis 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.