Django 6.1.3

12.6 Caching, signals, tasks, and files

Thread-local languages and aware datetimes

How do django.utils.translation.activate and django.utils.timezone.activate 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.published_at) 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/New_York". Both subsystems achieve that ambient isolation through a single shared primitive from asgiref: asgiref.local.Local.

Ambient per-request state via asgiref.local.Local

Open django/utils/timezone.py (line 61) and django/utils/translation/trans_real.py (line 26): both declare the exact same module-level container:

_active = Local()

Under synchronous WSGI threads, asgiref.local.Local isolates attributes per OS thread (just like threading.local); under asynchronous ASGI coroutines, it isolates attributes per asyncio task using Python’s contextvars.ContextVar 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":

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:

  1. Always store and compute in UTC: django.utils.timezone.now returns a timezone-aware UTC datetime.datetime. Database backends (SQLite, PostgreSQL, MySQL, Oracle) convert aware datetimes to UTC before writing and return aware UTC datetimes on read.
  2. 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) calls template_localtime, converting the stored UTC timestamp (2026-11-25T10:15:00+00:00) into the active Local timezone (2026-11-25T05:15:00-05:00 under "America/New_York").
  3. 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 aware datetime.datetime (TypeError: can't compare offset-naive and offset-aware datetimes). When a naive datetime reaches DateTimeField.get_prep_value under "USE_TZ = True", Django emits a RuntimeWarning ("DateTimeField Story.published_at received a naive datetime ... while time zone support is active.") and silently coerces it via 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 with django.utils.timezone.now or explicit datetime.timezone.utc / zoneinfo.ZoneInfo(...).

Watch "desk/"'s "bridge-bond-passes" UTC timestamp convert cleanly under django.utils.timezone.override ("America/New_York"), django.utils.translation.override ("fr") restore "en-us", and a naive datetime.datetime trigger RuntimeWarning inside DateTimeField.get_prep_value live:

Recorded on Django 6.1.3 ch12-services script
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.