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

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

```python
_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 `await`ed 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 (`django/utils/translation/trans_real.py:activate` & `LocaleMiddleware` (`django/middleware/locale.py:LocaleMiddleware`)):** `LocaleMiddleware.process_request` inspects the URL path prefix, language cookie, and `"Accept-Language"` header via `get_language_from_request`, calls `django.utils.translation.activate(language)` (storing a cached `DjangoTranslation` catalog on `"_active.value"`), and sets `"request.LANGUAGE_CODE"`. On exit, `LocaleMiddleware.process_response` stamps `"Content-Language"` and `"Vary: Accept-Language"` (feeding directly into `UpdateCacheMiddleware` from section 12.2!). Notice also why calling non-lazy `gettext()` at module import time breaks: `DjangoTranslation._add_installed_apps_translations` raises `AppRegistryNotReady` before `Apps.ready` — always use `gettext_lazy` in model/form definitions so evaluation waits until render time!
- **Timezones (`django/utils/timezone.py:activate` & `django/utils/timezone.py:override`):** `activate("America/New_York")` stores `zoneinfo.ZoneInfo("America/New_York")` in `"_active.value"`. Calling `get_current_timezone()` returns `getattr(_active, "value", get_default_timezone())`, falling back to `"settings.TIME_ZONE"` (`"UTC"` on `"desk/"`). Crucially, because `activate()` mutates ambient state on the worker thread/task until overwritten or cleared by `deactivate()`, **always prefer `with timezone.override(tz):` and `with translation.override(lang):`** (both `contextlib.ContextDecorator` subclasses that save `"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:

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` (`django/utils/timezone.py: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` (`django/db/models/fields/__init__.py: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:

```text recording=ch12-services
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](../tooling.md).
