Django's Architecture: MVT, Projects and Apps

Django's Architecture: MVT, Projects and Apps in Django: A county courthouse is one building, and it is the thing you actually open to the public.

The Analogy: A County Courthouse and Its Divisions

A county courthouse is one building, and it is the thing you actually open to the public. It has a single street entrance, one security checkpoint everyone passes through, one clerk of court who keeps the master register of which divisions exist, and one set of house rules that apply in every room. You do not deploy a courtroom on its own; you open the courthouse, and the courtrooms come with it. That whole building, with its shared entrance and shared rules, is the unit that gets commissioned, staffed, and shut down as one.

Follow a single case through the building and the flow is rigid. The case arrives at the door and passes security screening, which is applied to every visitor without exception. The front desk reads the case number and, consulting the day's cause list, sends it to exactly one courtroom. In that courtroom a judge hears the matter, sends a clerk to the records office to pull the relevant file, and issues a ruling written onto the court's standard judgment form. The finished ruling then leaves the building the same way it came in. Nobody decides case by case whether to screen a visitor or check their identity; those steps are wired into the path itself.

The building is carved into divisions -- criminal, family, probate -- and each division is a self-contained slice of the courthouse. A division owns its own courtrooms, its own shelf in the records office, and its own set of forms, and it is coherent enough that you could in principle stand the same division up in a different courthouse across the county. The building is the deployable thing; the divisions are the reusable slices inside it. A well-drawn division owns one bounded piece of the court's vocabulary and everything about that vocabulary lives together.

The failure that catches every new clerk is building a division but forgetting to enter it in the master register. The rooms are constructed, the desks are staffed, the forms are printed -- and nothing happens. The listing office never sends a case there because, as far as the register is concerned, the division does not exist. The records clerks allocate it no shelf space, and any notice it tries to post goes unread. No alarm sounds; the division is simply invisible until someone writes the single line that adds it to the register. In Django that line is the app's entry in INSTALLED_APPS, and its omission is the first thing to check when a model has no table or a template cannot be found.


Syntax or Core Structure

Django's core contract is small enough to state in one breath: a view is a callable that takes a request and returns a response, and a URLconf is an ordered list that maps a path to a view. Everything else -- the ORM, templates, the admin -- is convenience layered on top of that. Here is the shape in real Django:

# catalog/views.py
from django.http import HttpResponse

def health(request):
    return HttpResponse("ok")        # request in, response out -- a complete view
# config/urls.py
from django.urls import path
from catalog import views

urlpatterns = [
    path("health/", views.health, name="health"),
    path("products/", views.product_list, name="product-list"),
    path("products/<int:pk>/", views.product_detail, name="product-detail"),
]

The list is scanned top to bottom and the first pattern that matches wins, so order is meaningful. To see the resolution rule without a running server, here is the same pipeline reduced to a plain Python REPL you can execute anywhere -- a path string goes in, a status and body come out:

def product_list(request):
    return (200, "list of products")

def product_detail(request, pk):
    return (200, "product " + str(pk))

def health(request):
    return (200, "ok")

# the URLconf is an ORDERED list of (pattern, view) pairs
routes = [
    ("/health/", health),
    ("/products/", product_list),
    ("/products/<int>/", product_detail),
]

def resolve(path):
    for pattern, view in routes:
        if "<int>" in pattern:
            head = pattern.split("<int>")[0]
            tail = path[len(head):-1]
            if path.startswith(head) and path.endswith("/") and tail.isdigit():
                return view(None, int(tail))
        elif pattern == path:
            return view(None)
    return (404, "not found")

for p in ["/health/", "/products/", "/products/7/", "/cart/"]:
    status, body = resolve(p)
    print(str(status) + " " + body)

Tracing it by hand: /health/ matches the first pattern and returns ok; /products/ matches the second; /products/7/ falls to the converter pattern, which peels 7 out of the path and passes it as pk; and /cart/ matches nothing, so the fallthrough returns a 404.

Output:

200 ok
200 list of products
200 product 7
404 not found

Technical Depth: How a Request Becomes a Response

MVT named against classic MVC

Django calls its pattern Model-View-Template, and the names collide with the classic MVC ones in a way that trips people up. The table pins each responsibility to a Django term and to the MVC term it corresponds to.

Django termResponsibilityClassic MVC name
ModelDefines data and runs queriesModel
ViewTakes a request, returns a responseController
TemplateRenders the final HTMLView
URLconfRoutes a path to a viewRouter

The one to internalise is that a Django "view" is the controller, not the page. The thing that produces markup is the template. A view that returns HttpResponse("ok") never touches a template at all, and that is completely legal.

The middleware onion

Before a request reaches your view and after your response leaves it, every request passes through the middleware stack. Middleware runs top-to-bottom on the way in and bottom-to-top on the way out, wrapping the view like the layers of an onion. That ordering is why authentication, session loading, and CSRF checks live in middleware: they must apply to every request uniformly, and one forgotten decorator on one view would be a hole. Reduced to plain Python, the wrapping order is visible:

def view(request):
    print("view runs")
    return "response"

def security(next_layer):
    def layer(request):
        print("security in")
        result = next_layer(request)
        print("security out")
        return result
    return layer

def session(next_layer):
    def layer(request):
        print("session in")
        result = next_layer(request)
        print("session out")
        return result
    return layer

# stack declared outer-to-inner: security wraps session wraps view
handler = security(session(view))
handler("GET /")

Output:

security in
session in
view runs
session out
security out

The first middleware listed is the outermost layer, so it sees the request first and the response last. If you put a middleware that needs the logged-in user above the one that loads it, the user is not there yet -- ordering is a correctness concern, not a style choice.

Project versus app

A project is the deployable unit: it owns settings.py, the root URLconf, and the WSGI/ASGI entry points, and you have exactly one. An app is a self-contained slice -- models, views, templates, migrations -- and you have many.

shop/                      repository root
    manage.py
    config/                the project package
        settings.py
        urls.py            root URLconf
        wsgi.py
    catalog/               an app
        models.py
        views.py
        urls.py
        admin.py
    orders/                another app

An app becomes real only when it is registered. Until its name appears in INSTALLED_APPS, its models get no migrations and no tables, its templates are not discovered, and its admin registrations never run.


Real World Example: Routing a Day of Requests Through One Project

The program below is a single project that owns two apps -- catalog and orders -- reduced to runnable Python. It has an in-memory product table, a middleware layer that gates writes on authentication, a router that maps paths to views, and a driver that pushes a fixed day of requests through the whole stack and prints an access log.

# in-memory "database": the catalog app's Product table
products = [
    {"id": 1, "name": "pump", "active": True},
    {"id": 2, "name": "hose", "active": True},
    {"id": 3, "name": "clamp", "active": False},
]

def find(pk):
    for row in products:
        if row["id"] == pk:
            return row
    return None

# catalog app views
def product_list(req):
    names = ",".join(p["name"] for p in products if p["active"])
    return (200, names)

def product_detail(req):
    row = find(req["pk"])
    if row is None or not row["active"]:
        return (404, "no such product")
    return (200, row["name"])

# orders app view -- a write, so it needs auth
def order_create(req):
    row = find(req["pk"])
    if row is None or not row["active"]:
        return (404, "no such product")
    return (201, "order for " + row["name"])

# auth middleware: writes require an authenticated request
def with_auth(view, write):
    def wrapped(req):
        if write and not req["auth"]:
            return (403, "login required")
        return view(req)
    return wrapped

routes = [
    ("catalog:list",   product_list,  False),
    ("catalog:detail", product_detail, False),
    ("orders:create",  order_create,  True),
]

def resolve(name, req):
    for route_name, view, write in routes:
        if route_name == name:
            return with_auth(view, write)(req)
    return (404, "not routed")

# a fixed day of requests: (route name, request)
requests = [
    ("catalog:list",   {"auth": False}),
    ("catalog:detail", {"auth": False, "pk": 2}),
    ("catalog:detail", {"auth": False, "pk": 3}),
    ("orders:create",  {"auth": False, "pk": 1}),
    ("orders:create",  {"auth": True,  "pk": 1}),
    ("wishlist:add",   {"auth": True,  "pk": 1}),
]

ok = 0
for name, req in requests:
    status, body = resolve(name, req)
    if status < 400:
        ok += 1
    print(str(status) + " " + body)
print("ok: " + str(ok) + "/" + str(len(requests)))

Output:

200 pump,hose
200 hose
404 no such product
403 login required
201 order for pump
404 not routed
ok: 3/6

Read the log top to bottom. The catalog list names only the active products, so clamp never appears. Fetching product 2 succeeds; product 3 exists but is inactive, so the detail view reports it missing. The first order attempt is unauthenticated and the auth middleware stops it before the view runs at all -- exactly the uniform gate the middleware onion buys you. The second attempt carries auth: True and creates the order. The final request names a route that was never registered, and the resolver falls through to a 404.

This models the real Django request path faithfully -- ordered routing, middleware that wraps every view, a table read behind the view -- while staying fully deterministic. The products are fixed, iteration is over an explicit list in a fixed order, and no wall-clock or database sequence is involved, so the log is identical on every run.

The code is honest about its shape but has genuine flaws worth naming. The router matches route names by exact string equality, so it cannot capture a path parameter the way Django's <int:pk> converter does; the pk is smuggled in through the request dict instead of being parsed from the URL, which means the routing layer and the data it acts on have drifted apart. The with_auth gate checks only a boolean, with no notion of which user is logged in, so any authenticated caller can create an order for any product -- authorization is missing even though authentication is present. And product_detail collapses "no such product" and "product is inactive" into one 404, which is friendly to the public but hides a distinction the staff-facing side of a real shop would need.


Common Mistakes

  1. Confusing the view with the page. Newcomers expect a Django "view" to be the HTML. It is not -- it is the controller that returns a response. The template renders the markup. Naming a function product_page and stuffing template logic into it fights the framework's vocabulary.
  1. Forgetting to register the app. An app missing from INSTALLED_APPS gets no migrations, no tables, no template discovery, and no admin. When "Django cannot find my model," this list is the first thing to check, not the last.
  1. Getting middleware order wrong. Middleware that depends on the logged-in user must sit below the middleware that loads it. Place it above and the user is not populated yet, producing an intermittent AnonymousUser that only shows up under the right request.
  1. Omitting the trailing slash on URL patterns. Django's APPEND_SLASH redirects /products to /products/ for GETs, but a POST to the slashless URL is not redirected with its body intact. Inconsistent trailing slashes cause form posts to silently 404 or lose data.
  1. Building one giant app. A single app whose models.py passes a thousand lines turns every change into a merge conflict. Apps should own a bounded piece of domain vocabulary, not the entire domain.
  1. Splitting into an app per model. The opposite extreme is just as costly: dozens of one-model apps that only ever get imported together, so you spend your time wiring packages instead of writing features.
  1. Running model code without settings loaded. Any script that touches the ORM must run through manage.py or call django.setup() first. Import a model in a bare Python file and you get ImproperlyConfigured because DJANGO_SETTINGS_MODULE was never pointed at your project.
  1. Nesting the project package by accident. django-admin startproject config without the trailing . creates config/config/, an extra layer every new hire then has to have explained. The trailing dot puts the package at the repository root.
  1. Treating runserver as production. The development server is single-purpose: local development. It is not hardened, not fast, and not meant to face the internet. Production runs under gunicorn or uvicorn behind a real web server.

Best Practices

  • Keep views thin. A view should orchestrate: validate input, call into models or services, choose a response. Push query logic onto model managers and rendering onto templates so the view stays readable.
  • Name your URL patterns and reverse them. Give every path() a name and build links with reverse() or {% url %} rather than hardcoding paths. When a URL changes, one edit fixes every reference.
  • Namespace app URLs. Set app_name in each app's urls.py so patterns are addressed as catalog:detail. Two apps can then both have a detail route without colliding.
  • Draw app boundaries around domain vocabulary. Put the models that change together and are meaningless apart into one app. orders owning Order, OrderLine, and Payment is the right grain.
  • Register apps deliberately. Treat INSTALLED_APPS as the source of truth for what exists. When you add an app, add it here in the same commit so the migration and the registration never drift.
  • Run check --deploy before shipping. python manage.py check --deploy audits your settings for production footguns -- missing security headers, debug left on -- and catches them before your users do.
  • Keep the dev server out of production. Serve under an ASGI or WSGI server, and let a real web server or platform terminate TLS and serve static files. runserver stays on your laptop.
  • Let the framework do the boring 80%. Reach for Django's built-in auth, forms, and admin before writing your own. The value of a batteries-included framework is precisely that these decisions are already made and tested.

Practice Exercises

  1. Trace a request. Take the path /products/42/ and walk it through the pipeline in order: WSGI server, middleware in, URL resolver, view, model, template, middleware out. At each stage write one sentence naming what happens and what it hands to the next stage.
  1. Draw the app boundaries. You are building a bookshop with books, authors, customers, orders, and reviews. Group these into apps, justify each boundary in one sentence, and name the model that would be most tempting to put in the wrong app.
  1. Fix the middleware order. You have three middlewares: one loads the session, one loads the user from the session, and one logs the user's name on every request. Given they are declared in the wrong order and the log shows AnonymousUser, write the correct top-to-bottom order and explain why.
  1. Extend the router. Take the plain-Python resolve function from the Real World example and add a catalog:search route that takes a query field and returns the names of active products containing it. Give the expected output for the query "se" against the sample table, and state whether your route needs the auth gate.