Django Conventions¶
How to work inside the
backend/law_ai/Django package: the settings split, async ORM discipline, Channels routing, Celery naming, migration gotchas and strict typing.Closes BL-20260503-18. Conventions for working inside the
backend/law_ai/Django package introduced by ADR 0001. Read alongside docs/architecture.md and AGENTS.md §"Coding Standards".
1. Settings split¶
Settings live in backend/law_ai/settings/, one module per environment:
| Module | Loaded by | Purpose |
|---|---|---|
settings/base.py |
every other module via from .base import * |
Shared defaults; reads env via django-environ (Env(...) declarations at the top). Also where LLM_PROVIDER_CHAIN and the Claude/xAI/Ollama credential settings are declared (spec 034/035/050). |
settings/dev.py |
manage.py runserver, make dev |
DEBUG=True, ENVIRONMENT="development", ALLOWED_HOSTS=["*"]. Nothing else — CORS (a fixed 2-origin allowlist), DRF throttling, and the API-key default-open fallback are all inherited unchanged from base.py; see docs/security.md. |
settings/test.py |
pytest.ini --ds=law_ai.settings.test |
SQLite in-memory DB by default (override DATABASE_URL for Postgres-backed integration tests), in-process Celery (task_always_eager), in-memory Channels layer, DRF throttling relaxed to 100000/min. Also hard-blanks every LLM provider credential — CLAUDE_CODE_OAUTH_TOKEN="", ANTHROPIC_API_KEY="", OLLAMA_BASE_URL pointed at a closed port — so make test can never issue a real, billed Claude call or block on a live Ollama, even if those creds are set in your shell/.env. |
settings/prod.py |
DJANGO_SETTINGS_MODULE=law_ai.settings.prod |
DEBUG=False, ENVIRONMENT="production", plus the SECURE_*/HSTS/X-Frame-Options hardening block (see docs/security.md). Whitenoise's compressed-manifest static storage is actually a base.py default shared by every environment, not prod-specific. There is no Django cache backend (CACHES) configured anywhere yet, in any environment. |
Rules:
- Never read
os.environoutsidebase.py. All reads go through theEnv(...)declaration at the top ofbase.pyso types and defaults are explicit. - Do not import from
dev.py/prod.pyfrom application code — onlylaw_ai.core.settings_proxy(see §2). - Adding a new setting: declare it in
Env(...), assign it inbase.py, override per-env only when the value must differ.
2. settings_proxy usage¶
law_ai.core.settings_proxy is a thin lazy wrapper that lets domain modules read settings without importing django.conf directly. This keeps services unit-testable without booting Django.
from law_ai.core.settings_proxy import settings_proxy as settings
def ollama_configured() -> bool:
return bool(str(getattr(settings, "OLLAMA_BASE_URL", "") or "").strip())
(This mirrors the real pattern in law_ai.core.llm.providers.OllamaProvider — there is no wrapping client class; providers read settings_proxy directly and make their own httpx calls.)
- Use
settings_proxyin services, agents, tools, tasks — anywhere outside Django's HTTP/admin/ORM layer. - Use
from django.conf import settingsonly inside views, middleware, management commands, or migrations. - Never cache the proxy values at import time (
X = settings.FOOat module top); always read inside the function so test overrides viaoverride_settingsapply. - Import it as
settings_proxy as settings—settings_proxyexports only thesettings_proxyinstance, not a baresettingsname. All real call sites in the codebase use this alias.
3. Async ORM discipline¶
Django 5's ORM is async-capable, but this codebase does not currently use the async-native entry points anywhere — a repo-wide search for .acreate(, .asave(, .aget(, or async for ... in Model.objects outside tests returns zero hits. The established pattern instead is to keep the ORM out of async code paths entirely:
core/provenance.pyis the reference case. Its_persist()helper explicitly detects whether it's running inside an event loop (_in_async_context()) and, if so, skips the direct Django ORM write — the comment notes plain ORM calls raiseSynchronousOnlyOperationthere — and instead dispatches to thepersist_audit_eventCelery task, which runs in a genuine sync worker context.ingestionapp/services/approval.py::commit_approved_reviewis the other real pattern:await sync_to_async(review.save)(update_fields=[...])— a one-offsync_to_asyncwrap around a single-row save, called from async code. This is the codebase's actual convention for a single-row write that must happen from within an async function, notawait instance.asave().- If you're writing new async code that needs the ORM: prefer handing the write to a Celery task (matches
provenance.py) when the caller doesn't need the result inline; fall back tosync_to_async(...)around a single call (matchesapproval.py) when it does.await Model.objects.acreate(...)/await instance.asave()/await Model.objects.aget(...)are valid Django 5 APIs and fine to introduce, but doing so establishes a new pattern for this codebase, not an existing one — don't assume they're already the norm. - Multi-row transactions: wrap in
sync_to_asyncbecausetransaction.atomicis sync-only. Keep the transaction body small. - No async signals:
post_save/pre_savehandlers are sync; do heavy work via Celery instead of in a signal. - Connection lifetime: if you do call the ORM's async entry points directly from a long-running async task or Channels consumer, close the connection in teardown (
await connection.aclose()) to avoid leaks — but note no code in this repo does this today, because (per above) nothing calls the ORM directly from async context; the Celery-dispatch pattern sidesteps the question by never opening an async-context connection in the first place.
LangGraph's checkpointer uses raw asyncpg/psycopg outside the ORM (AsyncPostgresSaver.from_conn_string). That is the only sanctioned non-ORM path; everything else routes through Django.
4. Channels routing¶
WebSocket routing is split across two files:
- backend/law_ai/asgi.py builds the
ProtocolTypeRouterand importswebsocket_urlpatterns. - backend/law_ai/agentsapi/routing.py is where the actual
re_pathlist lives — add new consumers here, not inline inasgi.py.
# asgi.py
from law_ai.agentsapi.routing import websocket_urlpatterns
application = ProtocolTypeRouter({
"http": django_asgi_app,
"websocket": AuthMiddlewareStack(URLRouter(websocket_urlpatterns)),
})
# agentsapi/routing.py
websocket_urlpatterns = [
re_path(r"^ws/agents/(?P<run_id>[\w\-]+)/?$", AgentRunConsumer.as_asgi()),
]
- One consumer per top-level resource. Consumers live next to their REST router (e.g.
law_ai.agentsapi.consumers.AgentRunConsumer). - Auth is not
self.scope["user"].AgentRunConsumerdoesn't use Channels' session/user auth at all — it reads?api_key=/?token=from the query string (browsers can't set headers on a WS handshake) or anX-API-Keyhandshake header for non-browser clients, and compares it againstAGENT_API_KEYdirectly. With that setting unset, the socket accepts any connection. See docs/security.md for the full picture, including that per-router keys (ANALYSIS_API_KEY, etc.) don't apply to WS connections. - Always use channel groups for fan-out (
await self.channel_layer.group_add(...)) so multiple subscribers see the same trace stream. - Never block the consumer loop on Neo4j or LLM calls — fan out to a Celery task and stream results back via the channel layer.
5. Celery task naming¶
Celery app: law_ai.celery.app (Celery("law_ai")).
- Module location: tasks live in
<app>/tasks.py(e.g.law_ai.ingestionapp.tasks,law_ai.core.tasks). One file per Django app. - Naming: the
name=argument is required, dotted, and lowercase. Real examples:law_ai.core.persist_audit_event,law_ai.core.tasks.autonomy_cycle,law_ai.ingestionapp.quarantine_extraction,law_ai.ingestionapp.commit_approved_reviews. Note the prefix isn't perfectly uniform yet — some names include the.tasksmodule segment, some don't — so match whichever pattern the file you're editing already uses rather than inventing a third variant.
@shared_task(name="law_ai.ingestionapp.quarantine_extraction", ignore_result=True)
def quarantine_extraction(payload: dict) -> str:
...
ignore_result: setTruefor fire-and-forget tasks (ingestion, audit fallback writes) andFalsewhen a caller needs the return value (e.g.autonomy_cycle, invoked by the beat schedule and bymake autonomy-run).- Queues: there is currently one worker and two queues, not a per-family scheme —
docker-compose.yml'sworkerservice runscelery -A law_ai worker --beat -l info -Q autonomy,celery. No task in the codebase passes aqueue=kwarg to@shared_task; everything not explicitly routed toautonomylands on the defaultceleryqueue. A per-family queue split (ingestion,analysis,audit, …) is a reasonable future direction but is not implemented — don't write code that assumes it exists. - Idempotency: every task body must be safe to re-run. The real tasks do this with
update_or_create(quarantine_extraction) or by explicitly skipping already-committed rows (commit_approved_reviews, per its docstring). Celery retries are on by default. - No ORM transactions inside
apply_asynccallbacks — write the row first, dispatch the task with the row's PK, let the task fetch.
6. Migration gotchas¶
These come from real incidents shipped against backend/law_ai/:
- SQLite test DB vs. Postgres prod DDL.
pytest.iniruns migrations against SQLite in-memory. Postgres-only DDL (jsonb,timestamptz,pg_trgm, multi-statementRunSQL) breaksmigrateduring test setup. Workaround: gate inside aRunPythonop onschema_editor.connection.vendor == "postgresql"and provide a portable SQLite-compatible DDL fallback. Reference example: backend/law_ai/ingestionapp/migrations/0001_initial.py. - SQLite refuses multi-statement strings in
cursor.execute. Always split on;before callingschema_editor.execute(stmt)even when targeting both backends from one DDL blob. RunPython'sappsarg usesfrom_state.apps— the model declared in the same migration'sstate_operationsis not yet visible. Don't callapps.get_model("ingestionapp", "PendingReview")from aRunPythonpaired viaSeparateDatabaseAndStatewith aCreateModel. Use raw SQL or import the real model class instead.- Adopting a legacy raw-SQL table without dropping rows: wrap with
migrations.SeparateDatabaseAndState(state_operations=[CreateModel(...)], database_operations=[RunPython(_create_via_legacy_ddl, _drop)])and make the legacy DDL idempotent (CREATE TABLE IF NOT EXISTS,ADD COLUMN IF NOT EXISTS). - LangGraph checkpointer tables live in their own schema.
LANGGRAPH_CHECKPOINTER_SCHEMA(default"langgraph") is created bymanage.py ensure_checkpointer(run bymake migrateand by the compose boot chain), andcheckpointer_conn_string()(agents_runtime/graphs/runtime.py) appendsoptions=-csearch_path=<schema>to the saver's libpq URL, soAsyncPostgresSaver.setup()— whichensure_checkpointernow runs eagerly rather than leaving to first use — createscheckpoints/checkpoint_blobs/checkpoint_writes/checkpoint_migrationsinsidelanggraph, notpublic(BL-20260811-25). Two consequences: a Django model may safely reuse those table names, and any deployment that ran the old code has orphaned checkpoint tables inpublic— eitherALTER TABLE … SET SCHEMA langgraphthem once or accept that in-flight threads restart. If the checkpointer cannot be initialized at boot,ensure_checkpointerprints a loud error; setLANGGRAPH_CHECKPOINTER_REQUIRED=trueto make that abort the boot instead of degrading to an unpersisted runtime (BL-20260811-27).
7. Typing Django code under mypy --strict¶
backend/pyproject.toml loads mypy_django_plugin.main and mypy_drf_plugin.main (from the django-stubs / djangorestframework-stubs dev deps) with django_settings_module = "law_ai.settings.test" — the only settings module that boots with no services and no env, which is what CI's lint job has (BL-20260429-04). The plugin runs a real django.setup(), so anything that raises at app-registry time takes mypy down with an INTERNAL ERROR, not a type error. If mypy suddenly dies with Error constructing plugin instance of NewSemanalDjangoPlugin, read the traceback: the bug is in an AppConfig.ready(), an admin.py, or a settings import, not in mypy.
The strict run is gated by a ratchet rather than a clean bill of health: scripts/mypy_ratchet.py compares per-file error counts against backend/mypy-baseline.txt and fails when a count grows or a file the baseline calls clean stops being clean. A file with no baseline entry — every file you create — must be strict-clean. Burn a legacy file down, then make mypy-baseline to bank it; the totals only ever fall.
Four traps specific to typing this codebase:
admin.ModelAdminis generic to the stubs but not subscriptable at runtime. Class bases are evaluated eagerly even underfrom __future__ import annotations, soclass FooAdmin(admin.ModelAdmin[Foo])raisesTypeErrorduringdjango.setup()and kills the whole app registry (and the suite). Use theTYPE_CHECKINGalias the threeadmin.pyfiles already show:_ModelAdmin = admin.ModelAdmin[Foo]underif TYPE_CHECKING:, plainadmin.ModelAdminin theelse, and subclass the alias. The same applies to any Django class the stubs make generic without a runtime__class_getitem__.RunPythoncallables take(apps: Apps, schema_editor: BaseDatabaseSchemaEditor) -> None— importAppsfromdjango.apps.registryandBaseDatabaseSchemaEditorfromdjango.db.backends.base.schema. Both imports are runtime-safe.Migration.dependenciesis a class variable in the stubs, so annotating it asdependencies: list[tuple[str, str]] = []is amiscerror ("cannot override class variable with instance variable"). WriteClassVar[list[tuple[str, str]]], or leave it unannotated and let the base type flow through.- DRF view methods need
(self, request: Request, *args: Any, **kwargs: Any) -> ResponsewithRequestfromrest_framework.request(not Django'sHttpRequest), andauthentication_classestyped aslist[type[BaseAuthentication]]rather than barelist.
celery and lxml publish no stubs and no py.typed; they are listed in the ignore_missing_imports override in backend/pyproject.toml rather than carrying per-import # type: ignore comments. Note that warn_unused_ignores is on, so a # type: ignore that the stubs make unnecessary is itself an error — do not add one speculatively.
8. Code review checklist (Django-specific)¶
- New settings declared in
Env(...)and assigned inbase.py. - No
os.environreads outsidesettings/base.py. - Domain code uses
law_ai.core.settings_proxy.settings_proxy(importedas settings), notdjango.conf.settings. - Async code doesn't call the ORM directly without either a Celery dispatch or an explicit
sync_to_asyncwrap (see §3) — and if it introducesacreate/asave/aget, that's a new pattern for this codebase, called out as such in the PR. - New WS consumers attached to a channel group; no blocking I/O inside the consumer; auth reviewed against the real query-string/header check in §4, not an assumed
scope["user"]. - New Celery tasks have an explicit, correctly-prefixed
name=and an idempotent body. - Migrations gate Postgres-only DDL on
vendor == "postgresql". -
python manage.py check --deploystill exits 0. -
make typecheckpasses: new files aremypy --strictclean and no existing file's count grew (§7).
Related docs¶
- ADR 0001 — why Django.
- docs/architecture.md — where each layer lives.
- docs/security.md — token + scope details for views and consumers.
- docs/local-ai.md — Channels + Celery interplay with the LangGraph runtime.