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

# Mutating settings at runtime and in tests

Why does assigning to a setting leave some Django subsystems holding stale values, and how does `override_settings` notify the rest of the framework?

Once `LazySettings` has evaluated, `settings` feels like an ordinary mutable Python object. In a test suite — or a quick debugging script — it looks completely natural to write `settings.TIME_ZONE = "America/Chicago"` and expect Django to switch timezones. Python accepts the assignment without complaint, and reading `settings.TIME_ZONE` back prints `"America/Chicago"`.

Yet half of Django never saw the change.

## Direct assignment versus `override_settings`

Run both approaches back to back on our booted newsroom project and watch what `django.utils.timezone.get_default_timezone` actually returns:

```text recording=ch02-startup
override_settings, setting_changed, and stale captured state
  initial default timezone -> 'UTC'
  TRAP after direct settings.TIME_ZONE = 'America/Chicago': timezone.get_default_timezone_name() -> 'UTC' (stale lru_cache)
  inside override_settings: type(_wrapped)=UserSettingsHolder  timezone='America/Chicago'
  after exit: type(_wrapped)=Settings  timezone='UTC'
  setting_changed(setting='TIME_ZONE', value='America/Chicago', enter=True)
  setting_changed(setting='TIME_ZONE', value='UTC', enter=False)
  TRAP override_settings(DATABASES=...): UserWarning: Overriding setting DATABASES can lead to unexpected behavior.
  TRAP override_settings(MIDDLEWARE=[]): existing WSGIHandler._middleware_chain unchanged=True; fresh WSGIHandler chain differs=True
```

When you execute `settings.TIME_ZONE = "America/Chicago"` directly, `LazySettings.__setattr__` pops `"TIME_ZONE"` from the proxy's `__dict__` and writes the new string onto `LazyObject._wrapped` (`django/conf/__init__.py:LazySettings.__setattr__`, `django/utils/functional.py:LazyObject._wrapped`). Nothing else in the process is told. `django.utils.timezone.get_default_timezone` is decorated with `functools.lru_cache`, so it keeps handing back its cached `"UTC"` zone info (`django/utils/timezone.py:get_default_timezone`). The exact same quiet staleness affects cached template engines, database routers, storage backends, cache handlers, password validators, and compiled URL resolvers.

## How `override_settings` resets the framework

`override_settings` avoids mutating the underlying `Settings` object and notifies every listening subsystem inside `override_settings.enable` (`django/test/utils.py:override_settings.enable`).

If `"INSTALLED_APPS"` is among the overridden keys, `enable` updates the app registry *first* via `Apps.set_installed_apps` (`django/apps/registry.py:Apps.set_installed_apps`), rolling back with `Apps.unset_installed_apps` if an invalid app list raises an error so `settings` stays clean. Next it wraps the current `_wrapped` object inside a `UserSettingsHolder`, attaches the overridden attributes to that wrapper, saves the previous `_wrapped`, and assigns the new wrapper to `LazyObject._wrapped` on `settings` (`django/conf/__init__.py:UserSettingsHolder`).

Reassigning `_wrapped` triggers a special branch at the top of `LazySettings.__setattr__`: `if name == "_wrapped": self.__dict__.clear()`. Every cached setting on the proxy vanishes in one stroke so subsequent reads resolve through the new `UserSettingsHolder` layer.

Then Django broadcasts `setting_changed` for every overridden key with `enter=True` (`django/core/signals.py:setting_changed`). When the `with` block or test finishes, `override_settings.disable` restores the saved `_wrapped` (flushing `__dict__` a second time) and sends `setting_changed` with `enter=False` using `Signal.send_robust` so one failing receiver cannot prevent later receivers from cleaning up (`django/test/utils.py:override_settings.disable`).

Look inside `django/test/signals.py` to see how many caches across Django have to be unwound every time a setting changes: `update_connections_time_zone` clears `get_default_timezone` and resets active database connections' timezones (`django/test/signals.py:update_connections_time_zone`), `clear_cache_handlers` closes and rebuilds `caches` (`django/test/signals.py:clear_cache_handlers`), `reset_template_engines` clears `engines` and form renderers (`django/test/signals.py:reset_template_engines`), `root_urlconf_changed` clears URL resolver caches (`django/test/signals.py:root_urlconf_changed`), and `user_model_swapped` even reaches into five auth modules to rebind cached module-level `django.contrib.auth.backends.UserModel` globals (`django/test/signals.py:user_model_swapped`).

## Where even `override_settings` cannot reach

Even with a dozen built-in `setting_changed` receivers, three boundaries stay unreachable.

First, any module in your own codebase that wrote `TIMEOUT = settings.MY_TIMEOUT` at import time bound an ordinary Python integer into its module namespace forever. No `setting_changed` receiver knows that module exists; either read `settings` when the value is used or connect your own `setting_changed` listener.

Second, overriding `"DATABASES"` triggers `complex_setting_changed` and emits a `UserWarning` (`django/test/signals.py:complex_setting_changed`), as our recording confirmed on line 154.

> **History.** `COMPLEX_OVERRIDE_SETTINGS = {"DATABASES"}` cites ticket `#19031`: database connections carry open sockets, active transactions, and test-database creation state across `TestCase` rollbacks, so swapping `DATABASES` mid-test cannot reliably mirror a fresh boot.

Third — and easiest to miss — look at the final line of our recording:

```text recording=ch02-startup
override_settings, setting_changed, and stale captured state
...
  TRAP override_settings(MIDDLEWARE=[]): existing WSGIHandler._middleware_chain unchanged=True; fresh WSGIHandler chain differs=True
```

When a `WSGIHandler` is instantiated, `WSGIHandler.__init__` calls `BaseHandler.load_middleware` once and compiles `settings.MIDDLEWARE` into a closed-over chain of callables stored on `BaseHandler._middleware_chain` (`django/core/handlers/wsgi.py:WSGIHandler.__init__`). Changing `MIDDLEWARE` via `override_settings` does not rebuild any handler that already exists — only constructing a fresh handler picks up the new list (which is why Django's test `Client` builds a fresh handler on requests when middleware changes, whereas a long-lived `WSGIHandler` instance does not).

> **Trap.** `override_settings` swaps `LazyObject._wrapped` on the single process-global `settings` instance. It exists strictly for single-threaded test isolation, never for per-request toggles in a multi-threaded or async production worker where concurrent requests share the same `settings` object.

Settings are now configured, all eight apps are populated, every model is registered, cross-app foreign keys are wired, and every `ready()` hook has run. The booted process is finally ready for a web server to construct a handler — and compile that `MIDDLEWARE` list into the nested chain that wraps every incoming request. That machinery is where [Handlers, middleware, and async](../handlers.md) begins.
