How a Django project is structured: projects, apps and the journey of a request

TL;DR

Difficulty: Beginner

A Django project is configuration: settings, a root URL list and two entry points for web servers. An app is one piece of the business in one folder, active only when listed in INSTALLED_APPS.

  • Rails slices an application by layer (all models together), Django by subject (everything about bookings together). Django makes you decide the parts of your business on day one.
  • Draw app boundaries with the "who would you ring" test: group code by the person who would notice it breaking, one sentence per app without "and", dependencies pointing one way.
  • A request goes server, middleware, URL resolver, view, ORM, template, then back out through the middleware. Every hop is a line you can search for: Rails is guessable, Django is followable.

Django greets you with two words nobody explains: project and app. Then it calls a function a view and a page a template. This chapter explains the structure from the Django documentation itself, shows a way to draw app boundaries that holds up, and follows one request through a Limerick bicycle repair chain's application, file by file, next to its Rails twin.

The question behind this chapter

You type django-admin startproject, then python manage.py startapp, and Django has already used two words you were never introduced to: project and app. A few minutes later a settings file asks you to list something called INSTALLED_APPS, and the tutorial calls a Python function a "view" when every other framework you know would call it a controller. None of this is hard. It is just unexplained, and unexplained structure is what makes a new framework feel like someone else's house.

This chapter answers two questions. What is the difference between a Django project and a Django app? And what happens, step by step, between a browser asking for a page and Django sending one back? It is the first chapter of the Django series and the mirror of how a Rails application is structured, which answered the same questions for Ruby on Rails. If you have read the opening chapter of the programme, Django or Rails: two answers to the same question, you already know the two philosophies. Here they turn into folders and files.

Everything is written as of Django 5.0, released on 4 December 20231, with 5.0.3 the current patch release at the time of writing2. Django 5.0 supports Python 3.10, 3.11 and 3.121, and I use Python 3.12. Django 4.2 is the long term support release, and only one line in this chapter differs between the two, marked where it appears.

Example: the Django version of the spike

The series follows one invented business. Freewheel Cycles is a chain of six bicycle repair workshops in Limerick (freewheelcycles.example), founded by Niamh. It has 38 mechanics, about 1,150 repair bookings a week, 9,000 active customers and 2,400 spare parts in stock. It is replacing spreadsheets and a rented booking widget with its own web application: online booking with a time slot per mechanic, a live workshop board where job cards move from "waiting" to "in repair" to "ready", parts stock with a nightly reorder report, "your bike is ready" messages, and a back office for managers.

Its two developers, Aisling (four years of Python, mostly data analysis and a little Flask) and Cian (three years of TypeScript and React), built a two week spike of the core, booking and the workshop board, in both frameworks before choosing. The decision chapter tells how that ended. This series is the Django version of the spike: the same models, the same features, the same request, so you can compare like for like with the Rails series. The business and the people are made up. The code is real and runs on Django 5.0.

The short answer: Rails slices by layer, Django slices by subject

Here is the idea that makes everything else in this chapter fall into place, and it is not one the official documentation states in these words.

A Rails application is cut horizontally, by the kind of code. All models live in app/models, all controllers in app/controllers, all views in app/views3. To find the code for bookings you open three folders and look for the file named after bookings in each.

A Django project is cut vertically, by the subject the code is about. Each app is a folder for one area of the business, and inside it sit that area's own models, views, templates, admin configuration, tests and database migrations4. To find the code for bookings you open one folder, bookings, and everything is there.

Both are reasonable. They put the cost in different places. Rails lets you postpone the question "what are the parts of this business?" until the codebase is big enough to need an answer, which is why the Rails series has a whole chapter on growing a Rails application without it turning into a mess. Django asks the question on day one, the moment you type startapp, and it is entirely possible to answer it badly before you know the business well. Neither framework removes the question. They only choose when you face it.

Example: where the job card lives

Take one thing from the spike, the job card that moves across the workshop board, and look for it in both versions.

What you are looking forRails versionDjango version
The data and its rulesapp/models/job_card.rbrepairs/models.py
The code that handles the board pageapp/controllers/boards_controller.rbrepairs/views.py
The HTML for the boardapp/views/boards/show.html.erbrepairs/templates/repairs/board.html
The address of the pageconfig/routes.rbrepairs/urls.py, included from freewheel/urls.py
The back office screenan admin you build or addrepairs/admin.py
The database changesdb/migrate/ (one folder for everything)repairs/migrations/
The teststest/models/, test/controllers/, test/system/repairs/tests.py (or a tests package)

In Rails, the job card is spread across five folders that also hold everything else. In Django, it sits in one folder that holds nothing else. Aisling, used to Python packages, had the Django layout figured out within the hour. Cian, used to a React codebase organised by feature, found it obvious too. What neither of them found obvious was which folders Freewheel should have. That decision is the real work of this chapter, and it comes after the basics.

A project is configuration, an app is one piece of the business

Django's documentation defines the two words in a few lines, and both definitions are worth reading closely.

The tutorial says an app "is a web application that does something", such as a blog or a small poll app, and a project "is a collection of configuration and apps for a particular website"5. A project can contain several apps, and an app can be used in several projects. The reference documentation adds that an application is "a Python package that provides some set of features", and that a project is "defined primarily by a settings module"4. The reusable apps tutorial puts it most plainly: a Django application is a Python package specifically intended for use in a Django project6.

Two consequences follow, and they explain a lot of what feels strange at first.

  • The project is mostly configuration. Its package holds the settings, the top level list of addresses, and the two entry points a web server uses. Django's deployment guide says the settings module is "where your entire application is defined"7. The project is the wiring diagram. It is not where the business logic lives.
  • There is no application object. The reference says so directly: an app is a set of code that interacts with the framework, and Django keeps only a small configuration record for each one, an AppConfig4. An app becomes part of your project for one reason only: its name appears in the INSTALLED_APPS setting.

Example: Freewheel's spike as a project with five apps

The Django version of the spike has one project, called freewheel, and five apps. Here is the repository after the first day:

freewheel/                  # the repository root (any name works)
├── manage.py             # the command line tool for this project
├── freewheel/              # the project package: configuration only
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   ├── asgi.py
│   └── wsgi.py
├── accounts/             # who logs in, customers and their bikes
├── workshops/            # the six workshops and their mechanics
├── bookings/             # time slots and online booking
├── repairs/              # job cards and the workshop board
├── parts/                # spare parts, stock and the reorder report
└── templates/            # project wide templates, such as base.html

And here is where each model of the shared domain lives:

AppModelsOne sentence, no "and"
accountsUser, Customer, BikeKnows who people are
workshopsWorkshop, MechanicKnows where work happens and who does it
bookingsBookingTurns a request for a repair into a slot
repairsJobCard, PartUsageTracks a bike from arrival to collection
partsPartKeeps the stock of spare parts

Invoice is missing on purpose. Invoicing is not in the two week spike, and when it arrives it gets its own app. Two years on, Freewheel will also split customers out of accounts into an app of their own. Apps are easy to add early and awkward to split late, which is a theme of this whole chapter.

What startproject gives you, file by file

django-admin startproject creates exactly six files5. Each has one job.

  • manage.py is a small script that runs Django's commands for this project: runserver, migrate, startapp, shell, test and the rest. All it really does is set the environment variable DJANGO_SETTINGS_MODULE to your settings module and hand the command line to Django8. It is the same tool as django-admin, already pointed at your settings.
  • settings.py is a plain Python module of capitalised variables: the database, the installed apps, the middleware, the templates, the time zone, the secret key9. Because it is Python, it can import, compute and read the environment. That freedom is the source of both its convenience and the "how do I split my settings" debate further down.
  • urls.py is the root URL configuration, which the tutorial calls the "table of contents" of the site5. The setting ROOT_URLCONF points at it.
  • wsgi.py exposes an object called application that any server speaking the Web Server Gateway Interface (WSGI) can call7. WSGI is the long standing Python standard for connecting a web server to a Python application, defined in PEP 333310.
  • asgi.py does the same for the Asynchronous Server Gateway Interface (ASGI), the newer standard that also supports long lived connections such as WebSockets1112.
  • __init__.py is empty. It makes the folder a Python package, so the rest of the project can say freewheel.settings or freewheel.urls.

The development server, python manage.py runserver, uses the WSGI entry point and is, in the tutorial's own words, not meant for "anything resembling a production environment"5. In production you put a proper server in front: Gunicorn, uWSGI or Apache with mod_wsgi for WSGI, and Daphne, Hypercorn or Uvicorn for ASGI, the servers Django documents711.

FileCreated byResponsibilityYou edit it
manage.pystartprojectRuns commands with your settingsAlmost never
freewheel/settings.pystartprojectAll configurationOften, especially at the start
freewheel/urls.pystartprojectThe table of contents of addressesEach time an app gets pages
freewheel/wsgi.pystartprojectEntry point for WSGI serversRarely
freewheel/asgi.pystartprojectEntry point for ASGI serversRarely
app/models.pystartappData, fields and rulesConstantly
app/views.pystartappTurns a request into a responseConstantly
app/admin.pystartappBack office screens for the modelsOften
app/apps.pystartappThe app's configuration recordRarely
app/migrations/startappDatabase changes, one file per changeGenerated by makemigrations
app/tests.pystartappThe app's testsConstantly
app/urls.pyyouThe app's own addressesEach time a page is added
app/templates/app/youThe app's HTML templatesConstantly

Example: Freewheel's first commands

Aisling created the project in the repository root, so the outer folder and the project package do not end up with the same name twice in a row:

python3.12 -m venv .venv
source .venv/bin/activate
python -m pip install "Django>=5.0,<5.1"

# The trailing dot puts manage.py here instead of in a new folder
django-admin startproject freewheel .

# One command per app
python manage.py startapp accounts
python manage.py startapp workshops
python manage.py startapp bookings
python manage.py startapp repairs
python manage.py startapp parts

And here is the whole of manage.py after startproject, with the generated docstrings trimmed:

#!/usr/bin/env python
import os
import sys


def main():
    # Tell Django which settings to use, unless the environment already says
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "freewheel.settings")
    from django.core.management import execute_from_command_line

    # Hand "runserver", "migrate" and friends over to Django
    execute_from_command_line(sys.argv)


if __name__ == "__main__":
    main()

The second command is a one line summary of Django's attitude. Nothing about the project is discovered by magic. A variable says which settings module to load, and the settings module says everything else.

What startapp gives you, and what it leaves out

python manage.py startapp repairs creates a folder with __init__.py, admin.py, apps.py, a migrations package, models.py, tests.py and views.py5. Two things are deliberately missing.

  • There is no urls.py. The tutorial has you create one by hand and connect it to the project with include()5. An app that has no pages, such as one that only holds models, never needs one.
  • There is no templates folder. You create repairs/templates/repairs/ yourself. The doubled name looks redundant and is not, as the next section shows.

apps.py holds the configuration record. When INSTALLED_APPS lists an app by its plain name, Django picks up the single AppConfig subclass it finds in that app's apps.py4. The generated one sets the app's name and the type of automatic primary key:

# repairs/apps.py, as generated by startapp
from django.apps import AppConfig


class RepairsConfig(AppConfig):
    default_auto_field = "django.db.models.BigAutoField"
    name = "repairs"

Example: putting Freewheel's apps on the list

An app does nothing until it is installed. Aisling adds the five apps below Django's own contrib apps, and points Django at the custom user model in accounts:

# freewheel/settings.py (excerpt)
INSTALLED_APPS = [
    # Django's own apps, added by startproject
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    # Freewheel's apps
    "accounts",
    "workshops",
    "bookings",
    "repairs",
    "parts",
]

# A custom user model from day one: the Django docs highly recommend it
AUTH_USER_MODEL = "accounts.User"

The documentation highly recommends a custom user model for any new project, even if the default one would do13. Why that one line is so expensive to add later is a topic for the next chapter of this series, on starting a new Django project. For now it is enough to see that it names an app (accounts) and a model (User), and that Django will refuse to start if accounts is missing from the list.

INSTALLED_APPS is the guest list, and the order matters

INSTALLED_APPS reads like a list of dependencies. It works more like a guest list for a party where the first guest to answer a question gets to answer it. Several things depend on it:

  • Models only exist if their app is installed. Django builds its registry of models from the installed apps4. A model in an uninstalled app gets no table and no migrations.
  • Migrations belong to an app. python manage.py makemigrations repairs writes into repairs/migrations/, and each migration names the app it belongs to. The database history is split by subject, just like the code.
  • Templates and static files are searched in list order. With the default setting APP_DIRS: True, Django looks inside each installed app's templates folder, in the order of INSTALLED_APPS, and uses the first match it finds. The documentation underlines that the order "is significant"14.

That last point is the reason for the doubled folder name in repairs/templates/repairs/.

Example: two templates called board.html

Suppose Cian, in a hurry, saves the workshop board template as repairs/templates/board.html. A week later Aisling adds a booking calendar and saves it as bookings/templates/board.html, because to the front desk it is also a board. Both views ask for "board.html".

Django searches the installed apps in order. bookings comes before repairs in the list, so both pages now render the booking calendar. Nothing crashes. The mechanics just see the wrong screen, and nobody gives out about it until a customer does. It is the worst kind of bug, because it looks like a working page.

The fix is the namespacing the tutorial recommends15. Each app puts its templates inside a folder named after itself, so the names become repairs/board.html and bookings/board.html. They can never collide, and anyone reading render(request, "repairs/board.html", ...) knows which app the file lives in. The same order rule is also a feature. Put your own app above django.contrib.admin and your admin/base_site.html replaces the admin's, which is exactly how the documentation suggests you brand the admin14.

Drawing app boundaries: the "who would you ring" test

Django tells you what an app is. It does not tell you how many to have or where one ends and the next begins. The docs' examples (a blog, a poll app, a database of public records) are all things that could be packaged and reused on another site5. Most business applications are not built from reusable pieces. Freewheel's repairs app will never be installed in anyone else's project. So "could I publish this?" is the wrong test for most teams.

Here is the test I use instead, and the reason it works. Software boundaries last when they follow boundaries that already exist in the business. So for any piece of code, ask three questions:

  1. Who would you ring? If this part of the system misbehaved, which person in the business would notice first and want it fixed? Code that answers to the same person usually belongs together. Code that answers to different people usually does not.
  2. Can you describe the app in one sentence without "and"? "Tracks a bike from arrival to collection" passes. "Handles bookings and invoices" fails, and the "and" marks where to split.
  3. Do the dependencies point one way? If app A imports from app B, app B should not import from app A. When both point at each other, the boundary is in the wrong place, or one app is two apps.

At Freewheel, the answers to the first question map neatly. The front desk rings about bookings. The workshop lead rings about repairs. Whoever runs the stores rings about parts. Niamh and the managers ring about workshops. Nobody rings about accounts until a login fails, and then everyone does, which is why it sits at the bottom of the dependency chain and everything may depend on it.

Tap or click to enlarge

My view: for a business application, start with four to eight apps named after the parts of the business that have different people answering for them, put them in a strict order from "depends on nothing" to "depends on several", and treat an import that goes the wrong way as a design question, not a quick fix. Fewer, larger apps are easier to live with than many tiny ones in the first year. The Rails growing chapter reaches the same boundaries from the other direction, by carving them out of a layered codebase later.

Example: where PartUsage goes

When a mechanic fits a new chain to a bike, the job card records which part was used and how many. That record is PartUsage. It touches two apps: the job card is in repairs, the part is in parts. So which app owns it?

  • Who would you ring? If a fitted part is missing from a job card, the workshop lead notices, because the customer's repair is wrong. The stores manager only cares about the total stock that results. So the record answers to the workshop lead: repairs.
  • One sentence? "Tracks a bike from arrival to collection, including the parts fitted" still has no "and" doing real work. It fits.
  • One direction? repairs needs to know what a Part is. parts does not need to know what a job card is: its nightly reorder report needs stock levels, not repair history. So repairs depends on parts, never the reverse.

In code, a model in one app refers to a model in another by the string "app_label.ModelName", which keeps the import graph light:

# repairs/models.py
from django.db import models


class JobCard(models.Model):
    class Status(models.TextChoices):
        WAITING = "waiting", "Waiting"
        IN_REPAIR = "in_repair", "In repair"
        READY = "ready", "Ready"
        COLLECTED = "collected", "Collected"

    # A job card exists because of exactly one booking
    booking = models.OneToOneField(
        "bookings.Booking", on_delete=models.PROTECT, related_name="job_card"
    )
    mechanic = models.ForeignKey(
        "workshops.Mechanic", on_delete=models.PROTECT, related_name="job_cards"
    )
    # Django 5.0 accepts the choices class directly
    status = models.CharField(max_length=20, choices=Status, default=Status.WAITING)

    def __str__(self):
        return f"Job card {self.pk} ({self.get_status_display()})"


class PartUsage(models.Model):
    job_card = models.ForeignKey(JobCard, on_delete=models.CASCADE, related_name="part_usages")
    # repairs points at parts; parts never points back at repairs
    part = models.ForeignKey("parts.Part", on_delete=models.PROTECT)
    quantity = models.PositiveIntegerField(default=1)

Passing the Status class straight to choices= is new in Django 5.0, which no longer requires .choices on enumeration types1. On Django 4.2 you would write choices=Status.choices. The rest of the domain models get their full treatment in the ORM chapter of this series, so here they appear only as far as the request needs them.

MTV, MVC, and why Django calls the controller a view

Most web frameworks, Rails included, describe themselves with the pattern Model, View, Controller (MVC). The model holds data and rules. The controller receives the request and decides what to do. The view produces the HTML3. Django uses the same three ideas with different names, and the mismatch confuses almost everyone once.

Django's FAQ answers it directly. In Django's reading of MVC, a "view" describes which data the user sees, not how it looks, so the view is the Python function behind a URL. The template describes how the data is presented. And the controller? The FAQ says it is "probably the framework itself": the machinery that routes a request to the right view according to the URL configuration. If you want an acronym, the FAQ offers MTV, for model, template, view16.

JobRails nameDjango name
Holds the data and the business rulesModel (Active Record)Model (Django ORM)
Receives the request, decides what to load and which response to sendController actionView
Turns data into HTMLView (ERB template)Template
Maps a URL to the code that handles itRouter, config/routes.rbURL resolver, urls.py
Wraps every request in shared behaviourRack middlewareDjango middleware

My view: do not fight the names, translate them once and move on. When a Rails developer says "controller", a Django developer hears "view". When a Django developer says "view", a Rails developer should hear "controller action". Both communities drew the line between "deciding what to show" and "showing it" in the same place and labelled it differently.

Example: the bookings list in both vocabularies

For the list of today's bookings, Cian describes the Rails version: "The bookings controller's index action loads today's bookings, and the view renders them as a list." Aisling describes the Django version: "The bookings index view loads today's bookings, and the template renders them as a list." Same sentence, same code shape, two words swapped. This table was the first thing they wrote on the whiteboard when they compared spikes.

How a request travels through Django

Now the second question. A browser asks for a page. What happens between that request arriving and the HTML leaving? Django's documentation describes the URL part as an algorithm17, the middleware part as layers of an onion18, and the source of Django's request handler fills in the order between them19. Put together, there are eight steps.

  1. The server receives the request. Gunicorn, Uvicorn or another server accepts the connection and calls the application object in wsgi.py or asgi.py7.
  2. Django builds an HttpRequest. The handler turns the raw request into a Python object with the method, path, headers, cookies, and later the user.
  3. The request passes inwards through the middleware. Each middleware in the MIDDLEWARE setting gets the request in order, top to bottom18.
  4. The URL resolver finds the view. Django loads ROOT_URLCONF, walks urlpatterns in order and stops at the first pattern that matches17.
  5. The view runs. Django calls the view with the request and any values captured from the URL.
  6. The view uses the ORM. It builds database queries through models. QuerySets are lazy, so the query may run later than you think20.
  7. The template renders. The view hands a template name and a context of data to the template engine, which produces HTML.
  8. The response passes outwards through the middleware, in reverse order, and the server sends it to the browser18.
Tap or click to enlarge

The next five sections take the steps in turn, then a worked example traces one real request through Freewheel's code.

The server: WSGI or ASGI

WSGI is synchronous: one request, one call, one response. It has been the standard since 2003 and was updated for Python 3 in PEP 3333 in 201010. ASGI is its asynchronous successor and also handles WebSockets and other long lived connections12. Every new project gets both entry points. Django's own documentation is clear that its default ASGI handler runs your ordinary synchronous code in a thread, so switching server does not make an ordinary view faster by itself11.

For the Freewheel spike, Aisling runs Gunicorn in front of freewheel.wsgi:application. The live workshop board needs pages to update without a reload, and how to do that in Django (polling, htmx, or a WebSocket through ASGI) is a later chapter's question, on templates, htmx or an API.

Middleware: the onion

Middleware is Django's name for code that wraps every request. Django's documentation calls it "a light, low level plugin system" for altering input or output globally, and compares the layers to an onion: the request goes in through each layer to the view at the core, and the response comes back out through the same layers in reverse18. Any layer can answer on its own without calling the next one, and then the inner layers, including the view, never see the request.

startproject installs seven middleware classes. In order:

MiddlewareWhat it does on the way in or out
SecurityMiddlewareSecurity headers and HTTPS redirects, driven by settings
SessionMiddlewareLoads the session from its cookie, saves it on the way out
CommonMiddlewareNormalises URLs, for example adding a missing trailing slash
CsrfViewMiddlewareRejects form posts without a valid cross site request forgery token
AuthenticationMiddlewareAttaches request.user, using the session
MessageMiddlewareOne time messages such as "Booking saved"
XFrameOptionsMiddlewareStops other sites from showing your pages in a frame

The order is not decoration. AuthenticationMiddleware reads the session, so it must come after SessionMiddleware21. One detail is easy to miss: in Django's handler, the URL resolver runs inside the onion, after the request has passed through all the middleware19. So middleware sees every request, including ones that end in a 404. CommonMiddleware relies on exactly this: when APPEND_SLASH is on and a path without a trailing slash matches nothing, it redirects to the same path with a slash if that one exists21.

The URL resolver

Django finds the view by reading ROOT_URLCONF, importing that module and walking its urlpatterns list from top to bottom. The first pattern that matches wins17. Patterns match only the path: not the domain, not the query string after the question mark.

Patterns can capture parts of the path with path converters, written in angle brackets. Five come built in: str (any text without a slash, the default), int, slug (letters, numbers, hyphens and underscores), uuid and path (text including slashes)17. A converter both checks and converts, so <int:pk> passes your view a Python integer, not a string.

include() lets an app keep its own urls.py. When Django meets an include(), it cuts off the part of the path matched so far and passes the rest to the included list5. This is what lets the repairs app define its addresses without knowing where the project mounts it.

Every pattern can carry a name, and an app can declare an app_name. Together they let templates and code build URLs by name instead of by hard coded text, which the design philosophies page argues for: URLs should not be coupled to the Python code behind them22.

The view: a function or a class

A view is any callable that takes an HttpRequest and returns an HttpResponse23. In practice it comes in two shapes.

A function based view is a plain function. It is the clearest thing to read and the right default when you are learning.

A class based view is a class whose as_view() method returns a function. When a request arrives, that function creates an instance of the class, calls setup(), then dispatch(), which looks at the HTTP method and calls get(), post() and so on24. Django ships generic class based views (TemplateView, ListView, DetailView, CreateView and more) that handle the common shapes with very little code. They save typing once you know them and hide the flow until you do.

My view: write function based views until the same shape repeats three times, then reach for a generic view where it really fits. Both are fully supported, both return the same kind of response, and you can mix them freely in one project.

The ORM and the template: where the query really runs

The view uses the models to load data. One fact about Django's object relational mapper (ORM) changes how you read a view: QuerySets are lazy. Building one, filtering it and ordering it does not touch the database. The query runs only when the QuerySet is evaluated, for example when something loops over it20.

So in a typical view, the database query does not run in the view at all. It runs during template rendering, when the template's {% for %} loop iterates. Rails relations are lazy in the same way, so this is not a Django quirk. But it means that a slow page in Django is often a template problem in disguise: a loop that touches a related object on every row and sends one extra query each time. The ORM chapter of this series deals with that properly.

The template is the last step before the response. With APP_DIRS on, Django finds it in the app's templates folder, renders it with the context the view passed, and the render() shortcut wraps the result in an HttpResponse.

Worked example: tracing the bookings list request

Time to follow one request all the way through. It is the same request the Rails structure chapter followed through the Rails version: the page that lists today's bookings, earliest first. A manager at Freewheel's Dock Road workshop in Limerick opens it on the office laptop, and the browser sends:

GET /bookings/

The Rails version answers GET /bookings, without the final slash. Django's convention is to end paths with a slash, and if someone types /bookings anyway, CommonMiddleware redirects them to /bookings/ because APPEND_SLASH is on and only the version with the slash matches21. Same page.

The model the request needs

The Rails version gives Booking a scope called on_day. The Django equivalent is a method on a custom QuerySet, attached to the model as its manager with as_manager(), so it can be chained with other filters in the same way25.

# bookings/models.py
from django.db import models


class BookingQuerySet(models.QuerySet):
    def on_day(self, day):
        # All bookings that start on the given day, in the current time zone
        return self.filter(starts_at__date=day)


class Booking(models.Model):
    workshop = models.ForeignKey("workshops.Workshop", on_delete=models.PROTECT, related_name="bookings")
    mechanic = models.ForeignKey("workshops.Mechanic", on_delete=models.PROTECT, related_name="bookings")
    customer = models.ForeignKey("accounts.Customer", on_delete=models.PROTECT, related_name="bookings")
    bike = models.ForeignKey("accounts.Bike", on_delete=models.PROTECT, related_name="bookings")
    starts_at = models.DateTimeField()

    # Booking.objects.on_day(...) works like the Rails scope Booking.on_day(...)
    objects = BookingQuerySet.as_manager()

Unlike Active Record, the Django model lists its columns as fields. The migration is generated from those fields, not the other way round. The ORM chapter of this series looks at that difference properly.

Step 1 to 3: server, request object, middleware

Gunicorn receives the request and calls freewheel.wsgi.application. Django builds an HttpRequest with path set to /bookings/ and passes it through the seven middleware layers. SessionMiddleware loads the session from its cookie. AuthenticationMiddleware attaches request.user. Like the Rails version at this stage of the series, the page does not yet require a login: authentication gets its own chapter. CsrfViewMiddleware lets the request pass, because a GET request changes nothing.

Step 4: the URL resolver

Django reads ROOT_URLCONF, which startproject set to "freewheel.urls":

# freewheel/urls.py
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path("admin/", admin.site.urls),
    path("bookings/", include("bookings.urls")),
    path("", include("repairs.urls")),
]

The first pattern, admin/, does not match. The second, bookings/, does. Django cuts bookings/ off the path (the leading slash is never part of what patterns see) and hands the rest, an empty string, to bookings.urls:

# bookings/urls.py
from django.urls import path

from . import views

app_name = "bookings"

urlpatterns = [
    path("", views.index, name="index"),  # GET /bookings/
    path("<int:pk>/", views.detail, name="detail"),  # GET /bookings/42/
]

The empty pattern matches, and Django will call views.index(request) with no extra arguments. The second pattern is the Django counterpart of the Rails show route: its int converter would capture 42 from /bookings/42/ and pass it to the view as the integer pk. Because the app declares app_name = "bookings", templates can link to these pages by name, as {% url "bookings:index" %} or {% url "bookings:detail" booking.pk %}, and the links survive if the project later moves bookings to a different address.

You do not have to do this in your head. Django's resolve() function tells you which view a path reaches26, straight from the shell.

# python manage.py shell
>>> from django.urls import resolve
>>> match = resolve("/bookings/")
>>> match.func.__module__, match.func.__name__
('bookings.views', 'index')
>>> match.view_name
'bookings:index'
>>> resolve("/bookings/42/").kwargs
{'pk': 42}

Step 5 and 6: the view and the ORM

# bookings/views.py
from django.shortcuts import render
from django.utils import timezone

from .models import Booking


def index(request):
    # Today's bookings, earliest first, with customer and mechanic joined in
    bookings = (
        Booking.objects.on_day(timezone.localdate())
        .select_related("customer", "mechanic")
        .order_by("starts_at")
    )
    return render(request, "bookings/index.html", {"bookings": bookings})

Read it next to the Rails action, Booking.on_day(Date.current).includes(:customer, :mechanic).order(:starts_at), and the two are almost word for word the same. timezone.localdate() gives today's date in the project's time zone, as Date.current does in Rails. select_related follows the two foreign keys with a join, so the customer's and mechanic's names arrive in the same query instead of one extra query per booking27, which is the job includes does in the Rails version.

Here is the point from the ORM section, now in practice: this view never runs the query. It builds a lazy QuerySet and hands it to the template. The single SQL query runs during rendering, when the template's loop starts20.

Step 7: the template

{# bookings/templates/bookings/index.html #}
{% extends "base.html" %}

{% block content %}
  <h1>Today's bookings</h1>
  <ul>
    {% for booking in bookings %}
      <li>
        {{ booking.starts_at|time:"H:i" }}:
        {{ booking.customer.name }} with {{ booking.mechanic.name }}
        <a href="{% url 'bookings:detail' booking.pk %}">Open</a>
      </li>
    {% empty %}
      <li>No bookings today.</li>
    {% endfor %}
  </ul>
{% endblock %}

Django finds bookings/index.html by searching each installed app's templates folder in order, and finds it in bookings/templates/. The {% for %} loop is where the database is finally asked. {% extends "base.html" %} plays the part of the Rails layout: base.html sits in the project wide templates/ folder that Aisling added to the DIRS list of the TEMPLATES setting, and the page fills its content block where the Rails layout would yield. Then render() wraps the HTML in an HttpResponse with status 200.

Step 8: back out through the middleware

The response travels back through the seven layers in reverse. MessageMiddleware stores any unread messages, SessionMiddleware saves the session if it changed, SecurityMiddleware adds its headers, and XFrameOptionsMiddleware adds the header that keeps the page out of other sites' frames. Gunicorn sends the response to the laptop.

The same request in both frameworks

StepRails versionDjango version
AddressGET /bookingsGET /bookings/
Routeresources :bookings in config/routes.rbpath("bookings/", include(...)), then path("", views.index)
Code that handles itBookingsController#indexbookings.views.index
The day rulescope :on_day on the modelon_day on a custom QuerySet
The queryincludes(:customer, :mechanic)select_related("customer", "mechanic")
HTMLapp/views/bookings/index.html.erb inside the layoutbookings/templates/bookings/index.html extending base.html
How the template is chosenBy naming convention, rendered implicitlyBy the string passed to render()

The only real difference is the last row, and the next section explains why it matters more than it looks.

The same view as a class

For comparison, here is the list as a class based view, using the generic ListView:

# bookings/views.py, the class based alternative
from django.utils import timezone
from django.views.generic import ListView

from .models import Booking


class BookingListView(ListView):
    template_name = "bookings/index.html"
    context_object_name = "bookings"  # the name the template loops over

    def get_queryset(self):
        return (
            Booking.objects.on_day(timezone.localdate())
            .select_related("customer", "mechanic")
            .order_by("starts_at")
        )

In bookings/urls.py the pattern then points at views.BookingListView.as_view() instead of views.index. This time the class is a fair choice: a list of rows is exactly the shape ListView was made for, and it brings pagination with one more line when the list grows. Both versions produce the same page.

Rails and Django side by side

The two frameworks do the same jobs. The table puts each job's place in both.

JobRails 7.1Django 5.0
Create the skeletonrails new freewheeldjango-admin startproject freewheel .
A unit of the codebaseA folder per kind of code under app/An app per subject, each with its own models, views, templates
Packaged, reusable pieceEngine, "miniature applications"28Reusable app, installed with pip6
Run commandsbin/railspython manage.py
Web server entry pointconfig.ru (Rack)wsgi.py or asgi.py
Wrap every requestRack middleware, listed by bin/rails middleware29MIDDLEWARE setting
Map URLs to codeconfig/routes.rb, listed by bin/rails routesurls.py files joined by include()
Handle the requestController actionView (function or class)
Data and rulesActive Record modelDjango model
HTMLERB view in app/views/bookings/Template in bookings/templates/bookings/
Database changesdb/migrate/, one historymigrations/ per app
Configurationconfig/application.rb, config/environments/*.rb, credentialssettings.py and environment variables
Which pieces are activeGems in the Gemfile, loaded by BundlerINSTALLED_APPS
How code is foundAutoloading by naming convention (Zeitwerk)30Explicit Python imports

The last row is the one that changes your day. In Rails you find the next step of a request by knowing a rule: a BookingsController lives in app/controllers/bookings_controller.rb, and its index action renders app/views/bookings/index.html.erb unless told otherwise. The Rails Doctrine calls this convention over configuration31, and it is why a Rails developer can open an unfamiliar Rails app and guess right. In Django you find the next step by following a line you can search for: ROOT_URLCONF names a module, that module names a view by import, the view names a template by string. The Python principle behind it is PEP 20's "explicit is better than implicit"32, which Django's design philosophies adopt by name22.

Put shortly: Rails is guessable, Django is followable. Guessable is faster when you know the rules. Followable is faster when you do not. That is a real trade off, not a matter of taste, and it is a large part of why the learning curve chapter found the first weeks feel so different in each.

Example: Cian finds a page he has never seen

Cian has never written Python. On the spike's fourth day, Aisling asks him to change the column headings on the parts reorder page, which he has not seen before. He has the address, /parts/reorder/.

In the Django version, he opens freewheel/settings.py, finds ROOT_URLCONF = "freewheel.urls", opens that file, sees path("parts/", include("parts.urls")), opens parts/urls.py, sees path("reorder/", views.reorder_report, ...), opens parts/views.py, finds the function, and reads the template name in its render() call. Five hops, every one a line of text he could search for. He needed no prior knowledge of Django at all.

In the Rails version, he runs bin/rails routes, finds the line for /parts/reorder pointing at parts#reorder, and knows from the naming rule (which Aisling told him on day one) that this means app/controllers/parts_controller.rb, action reorder, template app/views/parts/reorder.html.erb. Two hops, but the second one only works if you know the rule.

By the second week Cian was faster in the Rails version. On day four he was faster in Django. Fair play to both, and a team that will onboard a good few newcomers should weigh day four more than it usually does.

Settings and environments

A project runs in at least three places: on a developer's laptop, in the test runner, and in production. Some settings must differ between them, such as DEBUG, the database, the allowed hosts and the secret key. The Django documentation tells you how Django finds the settings (the environment variable DJANGO_SETTINGS_MODULE9) but leaves the question of how to vary them to you. Two patterns dominate.

One settings module, values from the environment. There is a single settings.py. Everything that differs between environments is read from environment variables, following the configuration principle of the Twelve Factor App: a strict separation of configuration from code33. Django's own deployment checklist suggests loading the secret key this way rather than writing it in the file34.

Split settings modules. There is a package such as config/settings/ with base.py and one module per environment that imports the base and overrides what differs: local.py, production.py, test.py. The widely used project template cookiecutter django is laid out exactly like this, and it combines the split with environment variables read through django environ35.

django environ (the package django-environ, version 0.11.2 at the time of writing) is a small library that reads environment variables, optionally from a .env file, casts them to the right Python types, and turns a database URL into Django's DATABASES dictionary36. You can do all of this with os.environ and a few lines of your own. The library saves those lines and makes the casting explicit.

Two built in commands help whichever pattern you choose. python manage.py diffsettings shows every setting that differs from Django's defaults, which is the fastest way to see what a project really runs with. python manage.py check --deploy runs extra checks that only matter in production, such as DEBUG being off and secure cookies being on8.

My view: for a project the size of Freewheel's, one settings module with environment variables is the better choice. Every setting is in one file, so nobody has to work out which of four files wins. The differences between environments live in the environment, where the deployment platform can manage them. Split modules earn their keep when environments differ in structure (different installed apps, different middleware), not just in values. That is a judgement, not a rule: cookiecutter django's authors made the other choice for good reasons, mainly that a template serving thousands of different projects benefits from keeping production only settings visibly apart.

Example: Freewheel's settings read from the environment

# freewheel/settings.py (excerpt)
from pathlib import Path

import environ

BASE_DIR = Path(__file__).resolve().parent.parent

# Declare the type and default of each variable once
env = environ.Env(
    DEBUG=(bool, False),
    ALLOWED_HOSTS=(list, []),
)
# On a laptop, read a .env file if there is one; in production the platform sets real variables
environ.Env.read_env(BASE_DIR / ".env")

SECRET_KEY = env("SECRET_KEY")  # no default: refuse to start without it
DEBUG = env("DEBUG")
ALLOWED_HOSTS = env("ALLOWED_HOSTS")

# DATABASE_URL, for example postgres://freewheel:secret@localhost:5432/freewheel
DATABASES = {"default": env.db()}

TIME_ZONE = "Europe/Dublin"
USE_TZ = True

The .env file on Aisling's laptop holds her local values and never enters version control. A committed .env.example lists the variables with harmless placeholder values, so Cian can copy it on his first morning. In production, the hosting platform sets the same variables. If SECRET_KEY is missing, django environ raises Django's ImproperlyConfigured error and the project refuses to start, which is what you want: a loud failure on deploy beats a silent default in production36.

For tests, Django's test runner already switches some behaviour on its own, and a single test can change a setting with the override_settings decorator. A separate test settings module is only needed if the test environment differs in structure, and for the spike it did not.

The Rails version solves the same problem differently, with a file per environment in config/environments/ and encrypted credentials for secrets, as the Rails structure chapter describes. Both approaches are sound. Rails gives you the structure by default. Django gives you a Python file and trusts you to choose one.

For the person paying for this

If you are commissioning a Django application rather than building it, you do not need to read the code to judge whether it is well structured. Ask for these five things.

Ask forA good answerA warning sign
The list of apps, each with one sentenceFour to eight apps named after parts of your business, each sentence without "and"One app called core or main holding everything, or twenty tiny ones
Which app depends on whichA clear order, from apps that depend on nothing to apps that depend on several"They all use each other"
Where the settings for production come fromEnvironment variables set on the hosting platformPasswords or keys written in a file in the repository
The output of python manage.py check --deployNo warnings, or each one explainedNot run, or DEBUG on in production
Who owns the repository and the hosting accountsYou doThe developer, "for convenience"

The last row is not about Django at all, and it matters more than the others. Whoever builds it, the code, the accounts and the data should be yours from the first day. That is how I work on the web applications I build with Ruby on Rails, and it is a fair thing to ask of anyone building in Django.

Conclusion

A Django project is configuration: a settings module, a root URL list and two entry points for web servers. A Django app is one piece of the business in one folder, with its own models, views, templates, admin, migrations and tests, and it exists for the project only when it is listed in INSTALLED_APPS. Rails slices the same application by layer, Django slices it by subject, and the practical difference is when you have to decide what the parts of your business are. In Django, that is day one, and the "who would you ring" test is a good way to get it right: group code by the person who would notice it breaking, describe each app in one sentence without "and", and keep the dependencies pointing one way.

A request in Django travels from the server through the middleware onion, to the URL resolver, to a view, through the ORM and a template, and back out through the middleware in reverse. Every hop is written down somewhere you can search for, which makes Django followable where Rails is guessable. Learn the five words that differ (project, app, view, template, URLconf), and the rest of this series reads like the Rails series with a different accent. The next chapter starts the project for real: the first decisions, and the ones that are expensive to change later.

If you are planning a web application and want its parts drawn around your business rather than around a framework, book the free workshop: we map the parts together, and the first two weeks of work are on me.

Sources

  1. 1.

    Django Software Foundation, Django 5.0 release notes, 4 December 2023, https://docs.djangoproject.com/en/5.0/releases/5.0/

  2. 2.

    Django Software Foundation, Django 5.0.3 release notes, 4 March 2024, https://docs.djangoproject.com/en/5.0/releases/5.0.3/

  3. 3.

    Ruby on Rails Guides, Getting Started with Rails, version 7.1, https://guides.rubyonrails.org/v7.1/getting_started.html

  4. 4.

    Django Software Foundation, Applications, Django 5.0 documentation, https://docs.djangoproject.com/en/5.0/ref/applications/

  5. 5.

    Django Software Foundation, Writing your first Django app, part 1, Django 5.0 documentation, https://docs.djangoproject.com/en/5.0/intro/tutorial01/

  6. 6.

    Django Software Foundation, Advanced tutorial: How to write reusable apps, Django 5.0 documentation, https://docs.djangoproject.com/en/5.0/intro/reusable-apps/

  7. 7.

    Django Software Foundation, How to deploy with WSGI, Django 5.0 documentation, https://docs.djangoproject.com/en/5.0/howto/deployment/wsgi/

  8. 8.

    Django Software Foundation, django admin and manage.py, Django 5.0 documentation, https://docs.djangoproject.com/en/5.0/ref/django-admin/

  9. 9.

    Django Software Foundation, Django settings, Django 5.0 documentation, https://docs.djangoproject.com/en/5.0/topics/settings/

  10. 10.

    Phillip J. Eby, PEP 3333: Python Web Server Gateway Interface v1.0.1, Python Software Foundation, 26 September 2010, https://peps.python.org/pep-3333/

  11. 11.

    Django Software Foundation, How to deploy with ASGI, Django 5.0 documentation, https://docs.djangoproject.com/en/5.0/howto/deployment/asgi/

  12. 12.

    ASGI Team, ASGI Documentation: Introduction, https://asgi.readthedocs.io/en/latest/introduction.html

  13. 13.

    Django Software Foundation, Customizing authentication in Django: using a custom user model when starting a project, Django 5.0 documentation, https://docs.djangoproject.com/en/5.0/topics/auth/customizing/#using-a-custom-user-model-when-starting-a-project

  14. 14.

    Django Software Foundation, The Django template language: for Python programmers, loader types, Django 5.0 documentation, https://docs.djangoproject.com/en/5.0/ref/templates/api/#loader-types

  15. 15.

    Django Software Foundation, Writing your first Django app, part 3: template namespacing, Django 5.0 documentation, https://docs.djangoproject.com/en/5.0/intro/tutorial03/

  16. 16.

    Django Software Foundation, FAQ: General, "Django appears to be a MVC framework", Django 5.0 documentation, https://docs.djangoproject.com/en/5.0/faq/general/

  17. 17.

    Django Software Foundation, URL dispatcher, Django 5.0 documentation, https://docs.djangoproject.com/en/5.0/topics/http/urls/

  18. 18.

    Django Software Foundation, Middleware, Django 5.0 documentation, https://docs.djangoproject.com/en/5.0/topics/http/middleware/

  19. 19.

    Django Software Foundation, source code of django/core/handlers/base.py, Django 5.0.3, https://github.com/django/django/blob/5.0.3/django/core/handlers/base.py

  20. 20.

    Django Software Foundation, Making queries: QuerySets are lazy, Django 5.0 documentation, https://docs.djangoproject.com/en/5.0/topics/db/queries/#querysets-are-lazy

  21. 21.

    Django Software Foundation, Middleware reference, including middleware ordering, Django 5.0 documentation, https://docs.djangoproject.com/en/5.0/ref/middleware/

  22. 22.

    Django Software Foundation, Design philosophies, Django 5.0 documentation, https://docs.djangoproject.com/en/5.0/misc/design-philosophies/

  23. 23.

    Django Software Foundation, Writing views, Django 5.0 documentation, https://docs.djangoproject.com/en/5.0/topics/http/views/

  24. 24.

    Django Software Foundation, Introduction to class based views, Django 5.0 documentation, https://docs.djangoproject.com/en/5.0/topics/class-based-views/intro/

  25. 25.

    Django Software Foundation, Managers: creating a manager with QuerySet methods, Django 5.0 documentation, https://docs.djangoproject.com/en/5.0/topics/db/managers/#creating-a-manager-with-queryset-methods

  26. 26.

    Django Software Foundation, django.urls utility functions: resolve(), Django 5.0 documentation, https://docs.djangoproject.com/en/5.0/ref/urlresolvers/

  27. 27.

    Django Software Foundation, QuerySet API reference: select_related(), Django 5.0 documentation, https://docs.djangoproject.com/en/5.0/ref/models/querysets/#select-related

  28. 28.

    Ruby on Rails Guides, Getting Started with Engines, version 7.1, https://guides.rubyonrails.org/v7.1/engines.html

  29. 29.

    Ruby on Rails Guides, Rails on Rack, version 7.1, https://guides.rubyonrails.org/v7.1/rails_on_rack.html

  30. 30.

    Ruby on Rails Guides, Autoloading and Reloading Constants, version 7.1, https://guides.rubyonrails.org/v7.1/autoloading_and_reloading_constants.html

  31. 31.

    David Heinemeier Hansson, The Rails Doctrine, rubyonrails.org, 2016, https://rubyonrails.org/doctrine

  32. 32.

    Tim Peters, PEP 20: The Zen of Python, Python Software Foundation, 2004, https://peps.python.org/pep-0020/

  33. 33.

    Adam Wiggins, The Twelve Factor App: III. Config, 2011, https://12factor.net/config

  34. 34.

    Django Software Foundation, Deployment checklist, Django 5.0 documentation, https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/

  35. 35.

    cookiecutter django contributors, config/settings in the project template, GitHub, commit of 22 March 2024, https://github.com/cookiecutter/cookiecutter-django/tree/1a7e6a8414b8723ab2be4a48527c31aebd118e58/%7B%7Bcookiecutter.project_slug%7D%7D/config/settings

  36. 36.

    Daniele Faraglia and contributors, django environ 0.11.2: Quick Start, 1 September 2023, https://github.com/joke2k/django-environ/blob/v0.11.2/docs/quickstart.rst

Shelter

I’m running the London Marathon for Shelter. Sunday 25 April 2027

My personal fundraiser. Shelter, the National Campaign for Homeless People Limited, registered charity 263710 (England and Wales) and SC002327 (Scotland), registered with the Fundraising Regulator.

Donate to Shelter