01 Why both
Django brings what it has done best for twenty years: an ORM, migrations, a complete admin interface and management commands. FastAPI brings what Django does less well: fully asynchronous code, validation of requests and responses with Pydantic models, and API documentation that generates itself.
Rather than choose, the game takes both, with a strict split:
| Who | Does what |
|---|---|
| FastAPI | the game's pages (Jinja2 templates), the JSON API under /api/, its documentation at /api/docs, data validation |
| Django | the ORM and the migrations on PostgreSQL, the admin under /admin/, the commands (loading stations, creating grids), versioned static files |
All the application code is asynchronous: FastAPI receives the requests and calls Django's ORM with its asynchronous methods. Django itself only answers what FastAPI doesn't handle: the admin, and static files in development.
02 A single ASGI application
The server, uvicorn, only knows one application: FastAPI's. Django is mounted at the root, last, as a safety net.
The order matters. Django has to be configured before any model is imported, so django.setup() runs at the very top of the module, before the game's imports:
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")
# Models must be importable before the routes.
django.setup()
from django.conf import settings
from fastapi import FastAPI
from config.asgi import application as django_application
Then the routes are declared, and Django's mount comes last. Starlette, which FastAPI is built on, tries routes in the order they were declared: every game route comes before Django.
app.include_router(game_api) # /api/…
app.include_router(game_router) # the pages
# … /health, then /static outside development
app.mount("/", AppendSlash(NotFoundPages(django_application)))
On Django's side, the URL configuration is down to a single line, path("admin/", admin.site.urls). And Django's settings serve as the configuration for the whole application, FastAPI included: a single source for the database, the secrets and the options.
03 What Django's middlewares no longer do
There is a price: a request that stops in FastAPI never goes through Django's middlewares. No connection handling, no CSRF protection, no session. Everything that mattered had to be redone by hand, as ASGI middlewares placed around the whole application, Django included.
Database connections
Django keeps its connections open from one request to the next (CONN_MAX_AGE at 600 seconds, with a health check). Usually, it's its request start and end signals that close a connection that is too old or broken. FastAPI doesn't send them: left alone, a connection cut by the database would make every following request of the same worker fail. A middleware therefore does that job again:
class DatabaseConnectionsMiddleware:
async def __call__(self, scope, receive, send) -> None:
if scope["type"] != "http":
await self.app(scope, receive, send)
return
await _check_old_connections(perf_counter())
try:
await self.app(scope, receive, send)
finally:
await _close_old_connections()
A subtlety: Django's asynchronous ORM runs all its SQL queries in a single dedicated thread, and the connections live in that thread. The check therefore has to happen there too: it goes through sync_to_async, like the ORM itself.
CSRF protection
Players have no account: the browser identifies itself with an HttpOnly cookie carrying its identifier, and native clients with a header, X-Player-Id (which wins). A request that changes something, identified by the cookie alone, must carry an Origin or a Referer from the site. A page from another site can't add that header without a CORS preflight request that the game never allows. What remains is to refuse requests that change something and come from another origin, as Django's Origin check does:
async def same_origin(request: Request) -> None:
if request.method not in UNSAFE_METHODS:
return
source = request.headers.get("origin") or request.headers.get("referer")
if source is not None and urlsplit(source).netloc != request.headers.get("host"):
raise APIError(
status.HTTP_403_FORBIDDEN, ErrorCode.ORIGIN_REFUSED, "Request origin refused."
)
A browser always sends Origin on a POST request coming from another site. A request with neither Origin nor Referer therefore comes from a client that isn't a browser, like curl: CSRF doesn't concern it, so it goes through.
The admin session
Django's admin has its own sessions and authentication, which keep working for /admin/. But some pages of the game need to know whether the signed-in person is on the team, for example to "view the game as" a player, read-only. FastAPI then reads the admin's session cookie itself, as Django would, using the asynchronous session and ORM APIs.
The trailing slash
The pages are declared with a trailing slash, the Django way. AppendSlash wraps Django's mount: for a GET without a trailing slash, it checks whether a FastAPI route would match with the slash, and if so answers with a permanent redirect.
probe = {**scope, "path": f"{path}/"}
for route in scope["app"].router.routes:
if not isinstance(route, Mount) and route.matches(probe)[0] == Match.FULL:
return f"{path}/"
It ignores the API, paths that look like a file, and those starting with //, so as to never serve an open redirect to another site.
The 404 page
A path nobody knows ends up in Django, which answers with its own 404 page. NotFoundPages intercepts the response at the ASGI level: as soon as Django starts sending a 404 status, it sends the game's 404 page instead.
async def send_or_replace(message: Message) -> None:
nonlocal replaced
if message["type"] == "http.response.start" and message["status"] == 404:
replaced = True
await not_found_page(Request(scope, receive))(scope, receive, send)
elif not replaced:
await send(message)
The API, the admin and the static files keep their own responses. The 500 error page doesn't touch the database: it has to be able to show up precisely when the database is down.
04 A synchronous ORM in an asynchronous world
The routes and the game logic call Django's ORM with its asynchronous methods: aget, afirst, acreate, async for… Just one rule, but a strict one: no synchronous access in this code. An object.station that would sneakily trigger a query raises SynchronousOnlyOperation. Relations are therefore loaded ahead of time, with select_related and prefetch_related.
Templates never see a Django model. The data first goes through Pydantic models, built once the objects are loaded: a template only receives simple, typed data, and can't trigger a query by accident.
Transactions are the only place where the code becomes synchronous again: an ordinary function, with transaction.atomic(), called through sync_to_async, so that all its queries go through the same thread and the same transaction.
That single thread has a measurable consequence: a busy worker queues its database calls. Every request writes it in the logs:
GET /articles/ 200 app=3.4ms db=1.2ms/2 dbwait=0.1ms dbcheck=0.0ms
app is the total time, db the SQL time and the number of queries, dbwait the time spent waiting for that thread, dbcheck the time of the connection check. The SQL time is measured by a Django hook on each connection, and a context variable carries it up to the middleware. No address, no player identifier and no URL parameter appears in it.
05 Templates and URLs
The pages are rendered by a single Jinja2 environment, which borrows from Django what it does well: static() gives the versioned name of a file (stationdoku.3f9a1c2b7e4d.css), and the date filter formats dates like Django. The links, for their part, come from FastAPI:
@pass_context
def url(context: dict[str, Any], name: str, /, **path_params: object) -> str:
request: Request = context["request"]
return str(request.app.url_path_for(name, **path_params))
A template writes url('game:articles') and never contains a hard-coded address. Django's template engine is now only used for the admin.
06 Errors, in two languages
An API error has two parts: a message in English for developers, and a stable code, grid_not_found or origin_refused. The browser never shows the message: it translates the code into French. The same exception, APIError, gives JSON for the API and the game's 404 page for a page.
07 One schema, types everywhere
FastAPI describes the whole API in OpenAPI. This schema is turned into TypeScript types, and the front end only calls the API through them: the request body and the shape of the response are checked at compile time, from the address and the method. CI regenerates the types on every change and fails if they no longer match the Python code. A field renamed on the server therefore breaks the front end's compilation, not the game in production.
On the Python side, mypy runs in strict mode with Django's types. A single exception annotation remains in the mount: Django and Starlette describe the ASGI request with two different types for the same protocol.
08 The tests
The tests don't start a server: an HTTP client talks directly to the complete ASGI application, FastAPI and Django together, on a real PostgreSQL.
async with httpx.AsyncClient(
transport=httpx.ASGITransport(app=app),
base_url=BASE_URL,
headers={"Origin": BASE_URL, **headers},
) as client:
response = await client.post("/api/players")
client.headers["X-Player-Id"] = response.json()["id"]
They go through the same middlewares, the same origin check and the same mount as production.
09 In production
- uvicorn serves the application, with several workers, each with its own database connection. No gunicorn in front.
- Static files are collected by Django when the image is built, with a hash in their name, then served by Starlette with a one-year cache: a modified file changes its name.
- Migrations run before the new version starts, while the old one is still serving: every migration must work with the previous version.
- Deployment is blue-green: the new version starts next to the old one, Caddy only switches the traffic once its
/healthroute is healthy, then the old one stops.
10 The verdict
This setup keeps the best of each side: Django's admin and ORM without writing a line of them, FastAPI's speed and rigor for everything players see. The price is a handful of middlewares that redo what Django did on its own, each one small, commented and tested. And one rule never to forget: in this code, every call to the database is awaited with await.