12.6 Caching, signals, tasks, and files
Thread-local languages and aware datetimes
How do django and django store active state per thread or coroutine, and why does mixing naive and aware datetimes blow up at the database boundary?
Notice how neither gettext("Headline") nor template_localtime(story accepts a request argument! Yet on a multi-threaded WSGI server or concurrent ASGI event loop, Request A can render in French ("fr") using "Europe/Paris" at the exact same millisecond Request B renders in English ("en-us") using "America/. Both subsystems achieve that ambient isolation through a single shared primitive from asgiref: asgiref.
Ambient per-request state via asgiref.local.Local
Open django/ (line 61) and django/ (line 26): both declare the exact same module-level container:
_active = Local()
Under synchronous WSGI threads, asgiref isolates attributes per OS thread (just like threading.local); under asynchronous ASGI coroutines, it isolates attributes per asyncio task using Python’s contextvars so concurrent awaited requests on the same event-loop thread never stomp on each other’s language or timezone!
Trace how both modules read and mutate "_active":
- Translations (
activate&LocaleMiddleware):LocaleMiddlewareinspects the URL path prefix, language cookie, and.process_request "Accept-Language"header viaget_language_from_request, callsdjango(storing a cached.utils .translation .activate(language) DjangoTranslationcatalog on"_active.value"), and sets"request. On exit,.LANGUAGE_CODE" LocaleMiddlewarestamps.process_response "Content-Language"and"Vary: Accept-Language"(feeding directly intoUpdateCacheMiddlewarefrom section 12.2!). Notice also why calling non-lazygettext()at module import time breaks:DjangoTranslationraises._add_installed_apps_translations AppRegistryNotReadybeforeApps.ready— always usegettext_lazyin model/form definitions so evaluation waits until render time! - Timezones (
activate&override):activate("America/storesNew_York") zoneinfoin.ZoneInfo("America/ New_York") "_active.value". Callingget_current_timezone()returnsgetattr(_active, "value", get_default_timezone()), falling back to"settings(.TIME_ZONE" "UTC"on"desk/"). Crucially, becauseactivate()mutates ambient state on the worker thread/task until overwritten or cleared bydeactivate(), always preferwith timezoneand.override(tz): with translation(both.override(lang): contextlibsubclasses that save.ContextDecorator "old_timezone"and restore it inside__exit__!) — especially in middleware, background tasks, and management commands so one user’s timezone never leaks onto the next request handled by that worker!
UTC in storage, local time at the edges, and the naive datetime trap
When "USE_TZ = True" (Django’s default since 4.0 and enabled on "desk/"), Django enforces a strict architectural boundary:
- Always store and compute in UTC:
djangoreturns a timezone-aware UTC.utils .timezone .now datetime. Database backends (SQLite, PostgreSQL, MySQL, Oracle) convert aware datetimes to UTC before writing and return aware UTC datetimes on read..datetime - Convert to the active user’s timezone only at the presentation edge: When a template renders
{{ story,.published_at }} render_value_in_context(Chapter 10) callstemplate_localtime, converting the stored UTC timestamp (2026-11-25T10:) into the active15: 00+00: 00 Localtimezone (2026-11-25T05:under15: 00-05: 00 "America/).New_York" - Why naive datetimes break at the DB boundary: Python refuses to compare or subtract a naive
datetime(.datetime(2026, 11, 25, 10, 15) tzinfo is None) against an awaredatetime(.datetime TypeError: can't compare offset-naive and offset-aware datetimes). When a naive datetime reachesDateTimeFieldunder.get_prep_value "USE_TZ = True", Django emits aRuntimeWarning("DateTimeField Story) and silently coerces it via.published_at received a naive datetime ... while time zone support is active." make_aware(value, get_default_timezone())— which both crashes ambiguously during Daylight Saving Time fold/gap transitions and shifts timestamps silently by hours if"TIME_ZONE"is not"UTC"! Always construct timestamps withdjangoor explicit.utils .timezone .now datetime/.timezone .utc zoneinfo..ZoneInfo(...)
Watch "desk/"'s "bridge-bond-passes" UTC timestamp convert cleanly under django ("America/), django ("fr") restore "en-us", and a naive datetime trigger RuntimeWarning inside DateTimeField live:
6. Local timezone/language activation and naive DateTimeField
timezone_override: stored_utc='2026-11-25T10:15:00+00:00' active_ny='America/New_York' ny_local='2026-11-25T05:15:00-05:00' restored='UTC'
translation_override: active='fr' restored='en-us' local_type=asgiref.local._DefaultLocal
naive_datetime_field: warning='RuntimeWarning' is_aware_after_prep=True tz_after_prep='UTC'
That completes Part III · Presentation and systems! Everything we have dissected from Chapter 1 through Chapter 12 runs inside a web worker handling HTTP requests. Yet half of every developer’s day happens at the terminal — running manage.py, system checks, "runserver"'s dual-process autoreloader, and Django’s transaction-rolling test suite. We open Part IV · In practice next in Commands, checks, and testing.