Starting a new Django project: the first decisions, and which ones are hard to change later
TL;DR
Difficulty: Beginner
Sort every early decision by where it gets written down: pencil (settings), pen (code) or ink (migrations and stored rows).
- Ink before the first migrate: a custom user model, the primary key type, money as Decimal, PostgreSQL, a UUID for anything customers see.
- Pen before the first feature: the front end approach, templates and htmx or an API.
- Pencil before the first deploy: dependency tool, settings from the environment, WhiteNoise for static files.
- Rails asks its questions as flags on day one; Django's startproject decides quietly, so read every line of the generated settings once.
Django starts in under a minute. The harder question is which choices from this week will still be with you in three years. Here is a simple test for that, pencil, pen or ink, worked through on a real setup with Django 5.0 and Python 3.12: the environment, the settings, the custom user model in code, money, time zones and a first deploy.
The question behind this article
You have an empty folder, Python on your laptop and a product to build. Django will happily start in under a minute. The real question is a different one: which of the choices you make this week will still be with you in three years, and which can you safely leave until later?
That is the question this article answers, as of April 2024: Django 5.0 (released on 4 December 2023, the latest patch is 5.0.3) and Python 3.121. It is the second chapter of the Django series. The first one, how a Django project is structured, explains projects, apps and the path of a request, and I assume you have read it or know that ground. The Rails series has a matching chapter, starting a new Rails application: the first decisions, and I compare the two where it helps.
The example is the same invented business as in the whole programme. Freewheel Cycles is a chain of six bicycle repair workshops in Limerick (freewheelcycles.example), founded by Niamh, with 38 mechanics, about 1,150 repair bookings a week and 9,000 active customers. It is replacing spreadsheets and a rented booking widget with its own web application. Aisling has four years of Python, mostly data analysis and a little Flask. Cian has three years of JavaScript and TypeScript with React. Neither has used Ruby or Django in production. In the evaluation, both built a two week spike of the core in both frameworks, and the Django code in this series is the Django version of that spike. Which framework they finally chose, and why, is told in how to choose between Django and Rails. This chapter is only about the start: the same first decisions, made well in Django.
Business, people and numbers are made up. The commands and the code are real and run on Django 5.0.3 and Python 3.12.
Pencil, pen and ink: sort every early decision by where it gets written down
Most "first steps" guides give you a checklist. A checklist treats every item as equally urgent, and that is the problem: a team with six months of budget cannot think hard about twenty things in week one. You need to know which three deserve the thinking.
Here is the test I use. For every early decision, ask where it ends up being written down. There are three places, and they cost very different amounts to rub out.
- Pencil: the decision lives in settings or environment variables. The secret key, the allowed hosts, how static files are served, the email backend, even the dependency tool. Changing it is an afternoon: edit one file, redeploy.
- Pen: the decision spreads through your code. The front end approach (server rendered templates or an API behind a JavaScript app), the way apps are cut, the login library. Changing it costs in proportion to how much code you have written since. A small job in week one, weeks of work in month six.
- Ink: the decision is written into migrations and into stored rows. The user model, the primary key type, how money is stored, which database engine holds the data. Changing it means a data migration on a live database, often with downtime planned around it. Ink never gets easier to change, only harder with every row.
From that follows one rule of thumb, and it is the spine of this article:
Ink before the first migrate. Pen before the first feature. Pencil before the first deploy.
Two refinements make it sharper. First, a decision in ink should be made so that later changes become additions, not replacements. Adding a field to a model you own is an ordinary migration. Replacing the model that every foreign key points at is the expensive kind. Second, ink is not always where you expect it. Time zone handling looks like ink and on PostgreSQL turns out to be closer to pen, as you will see below. The test is where the decision is actually stored, not how important it sounds.
Example: Freewheel's first decisions, sorted
Aisling and Cian list what they must decide before they write the booking screen, and sort each item by where it will be written down.
| Decision | Where it is written | Layer | Decide before |
|---|---|---|---|
| User model (built in or custom) | first migration, every foreign key to users | Ink | first migrate |
| Primary key type | every table, every foreign key | Ink | first migrate |
| How money is stored | column types and every stored amount | Ink | first model with a price |
| Database engine | all stored data | Ink | first real data |
| Public booking reference (UUID or not) | a column, and links already in customers' inboxes | Ink | first email sent |
| Time zone handling | settings, plus every place code builds a datetime | Pen | first booking model |
| Front end approach | views, templates, JavaScript | Pen | first feature |
| How apps are cut | imports and migrations across apps | Pen | first feature |
| Dependency tool | one or two files | Pencil | first teammate joins |
| Settings from environment | settings.py and the hosting dashboard | Pencil | first deploy |
| Static files | settings and middleware | Pencil | first deploy |
Five rows are ink. That is where Aisling and Cian spend their thinking on day one. Everything else gets a sensible default and a note.
Rails asks you up front, Django decides quietly
This is the difference between the two frameworks at the start, and it changes where the danger sits.
rails new asks. The database, the JavaScript approach, the CSS framework and whether to skip tests are flags you type on the first line, and Rails 7.1 even writes a Dockerfile for you2. You cannot start a Rails application without at least seeing the choices.
django-admin startproject does not ask anything. It writes a small, readable settings.py and you are running. That is a deliberate part of Django's design: explicit configuration in plain Python, no generator magic, nothing you did not see. The price is that the defaults in that file quietly become decisions if nobody looks at them. In Rails the risk is choosing badly. In Django the risk is not noticing that you chose at all.
Example: what startproject decided for Freewheel without asking
Aisling runs startproject and reads the generated settings.py line by line3. These are the settings that matter for the ink and pen layers.
| Default in the generated settings | What it means | Keep it? |
|---|---|---|
DATABASES uses SQLite in a file db.sqlite3 | The data lives in one local file | No: PostgreSQL from day one (below) |
No AUTH_USER_MODEL setting | Every login points at Django's built in auth.User | No: custom user model before the first migrate |
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" | 64 bit integer primary keys | Yes |
TIME_ZONE = "UTC" and USE_TZ = True | Store and show UTC | Keep USE_TZ, set TIME_ZONE to Europe/Dublin |
LANGUAGE_CODE = "en-us" | American date formats and translations | Change to en-ie |
SECRET_KEY and DEBUG = True written in the file | Fine on a laptop, dangerous in Git | Move to the environment |
Two of these are ink: the database and the user model. One of them, USE_TZ = True, is a good default that only became the default in Django 5.01. Projects started on older versions had it switched on by the template too, but the setting's own default was False until 5.0, which is why you still meet older projects without it.
Step one: Python, a virtual environment and pinned dependencies
Before Django there is Python, and before your project's packages there is a virtual environment.
A virtual environment is a folder that holds its own Python interpreter link and its own installed packages, separate from everything else on your machine. The Python documentation describes it as lightweight and disposable: easy to delete and recreate, never copied between machines4. Each project gets its own, so Freewheel's Django version never fights with another project's.
The next question is how you record which packages, at which versions, the project needs. As of April 2024 there are four serious options:
| Tool | What you edit | What it writes | Good for |
|---|---|---|---|
| pip with pip tools | requirements.in (top level packages) | requirements.txt with every package pinned | Plain files every host understands |
| Poetry | pyproject.toml | poetry.lock | One tool for dependencies, environments and packaging |
| PDM | pyproject.toml (standard project metadata) | pdm.lock | People who want the newest packaging standards |
| uv | the same files as pip and pip tools | requirements.txt | Speed, but it is new |
Pip tools describes itself as pip-compile plus pip-sync: you list the packages you want, it resolves and pins every dependency, and a second command makes the environment match the list exactly5. Poetry replaces several older files with one pyproject.toml and a lock file you commit6. PDM calls itself a package manager that follows the latest Python packaging standards7. uv was announced by Astral on 15 February 2024 as a very fast installer and resolver written in Rust, designed as a replacement for pip and pip tools workflows8. At the time of writing it is six weeks old.
My view: for a first Django project with a small team, pip with pip tools is the best value. It produces a plain requirements.txt that every hosting platform and every Dockerfile already understands, there is almost nothing to learn, and because uv was built to drop into exactly this workflow, choosing pip tools today keeps that door open without betting on a six week old tool. Poetry and PDM are good tools. I would pick one of them when the team already knows it, not as a first lesson. Notice where this sits in the model: it is pencil. Switching tools later touches two files.
Example: Freewheel's environment and requirements
Aisling sets up the project folder. Python 3.12 is installed through the official installer or the operating system's package manager.
mkdir freewheel && cd freewheel
python3.12 -m venv .venv # the project's own environment
source .venv/bin/activate # on Windows: .venv\Scripts\activate
python -m pip install --upgrade pip pip-tools
She lists only what Freewheel asks for directly, with a version range, in requirements.in:
# requirements.in: what Freewheel uses directly
Django>=5.0,<5.1
psycopg[binary]>=3.1.8 # PostgreSQL driver, the version Django 5.0 recommends
django-environ>=0.11 # settings from environment variables
whitenoise>=6.6 # static files in production
gunicorn>=21.2 # the application server
Then she compiles and syncs:
pip-compile requirements.in # writes requirements.txt, every package pinned
pip-sync requirements.txt # makes .venv match the file exactly
The generated requirements.txt pins every package, including the ones Django pulls in. In April 2024 it starts like this (excerpt):
django==5.0.3
django-environ==0.11.2
gunicorn==21.2.0
psycopg[binary]==3.1.18
whitenoise==6.6.0
Both files go into Git. .venv does not: it is disposable, and Cian recreates his own with the same three commands.
The version range Django>=5.0,<5.1 is itself a small decision. Django 5.0 receives security fixes until April 2025, and Django 4.2, the long term support (LTS) release, until April 20269. Choosing 5.0 means planning an upgrade within a year, to 5.1 and then to the next LTS. Freewheel takes 5.0 for the newer features and puts the upgrade in the plan. A team that wants to upgrade as rarely as possible would start on 4.2 and lose little. The five year view of that trade is in five years with Django or Rails.
A template, or start from startproject?
There is a well known shortcut. Cookiecutter Django, a project template run by Daniel Roy Greenfeld and other volunteers, generates a complete project in one go. In March 2024 its README lists, among other things: Django 4.2, Python 3.12, settings from environment variables via django environ, a custom user model ready to go, registration through django allauth, PostgreSQL everywhere, Docker for development and production, and optional Celery, WhiteNoise and Sentry10.
That is a lot of good decisions, made by experienced people. It is also a lot of decisions made for you, and that is the honest trade.
My view: if the team already knows Django, Cookiecutter Django is a fine starting point and saves days. If the team is new to Django, as Freewheel's is, start from startproject and add each piece by hand. You end the first week knowing why every line in settings.py is there, and that knowledge is what lets you change pen and pencil decisions later without fear. Keep the template open in a browser tab as a reference: when you wonder how to wire something, see how they did it.
Example: why Aisling and Cian start bare
Aisling and Cian look at the Cookiecutter Django output for half an hour. Three things decide it for them. The template targets Django 4.2, and they want 5.0. It brings django allauth for sign up and social login, while Freewheel's customers book without accounts in version one. And it brings a Docker setup with several services that neither of them can yet explain. They start from startproject, and they copy two ideas from the template on purpose: settings from the environment, and a custom user model from the first commit. Both appear below.
PostgreSQL from the first day
Django supports several databases. As of Django 5.0, PostgreSQL 12 and higher is supported, with psycopg 3.1.8 or newer recommended as the driver11. SQLite works without any setup, which is why startproject chooses it, and it is a fine database for learning and for some small production sites.
For an application like Freewheel's, run PostgreSQL in development as well as production. Three reasons. The engines differ in small ways that bite late: the Django documentation lists SQLite specific limitations, among them how it handles decimal fields1112. Django ships extra PostgreSQL features in django.contrib.postgres (special field types, indexes, full text search) that you may want for searching parts or customers. And moving real data between engines later is ink: possible, but nobody's idea of a good weekend.
The Rails chapter reaches the same conclusion for Rails: starting a new Rails application.
Example: one database URL
Aisling installs PostgreSQL locally and creates the development database:
createdb freewheel_development
Django creates its own test database (test_freewheel_development) when the tests run, so she does not create that by hand. Her local connection string goes into a .env file, described in the next section:
DATABASE_URL=postgres://priya@localhost:5432/freewheel_development
Settings from the environment
The generated settings.py holds the secret key and DEBUG = True in plain text. That is fine for the first five minutes and wrong after the first commit. The Django deployment checklist says the secret key must be kept secret and suggests loading it from an environment variable13. The Twelve Factor App, a 2011 methodology by Adam Wiggins of Heroku, puts the principle simply: strict separation of configuration from code, with configuration in environment variables14.
You can read environment variables with os.environ and nothing else. Django environ, a small package by Daniele Faraglia and contributors, adds two conveniences: it reads a local .env file in development, and it turns a single DATABASE_URL into Django's DATABASES dictionary, with type conversion for booleans and lists15. The README also recommends committing an example file that lists the variables without real values. That is what Freewheel does.
This is pencil, so do not agonise. Pick one way, write it down, move on.
Example: the settings file Freewheel starts with
Here is the top of Freewheel's settings, rewritten from the generated file:
from pathlib import Path
import environ
BASE_DIR = Path(__file__).resolve().parent.parent
# Every value that changes between a laptop and production comes from the
# environment. Locally, a .env file (never committed) fills it in.
env = environ.Env(DEBUG=(bool, False))
environ.Env.read_env(BASE_DIR / ".env")
SECRET_KEY = env("SECRET_KEY") # fails loudly if missing
DEBUG = env("DEBUG") # False unless .env says otherwise
ALLOWED_HOSTS = env.list("ALLOWED_HOSTS", default=[])
# PostgreSQL everywhere, read from one URL:
# DATABASE_URL=postgres://user:password@localhost:5432/freewheel_development
DATABASES = {"default": env.db("DATABASE_URL")}
DEBUG defaults to False, so a server where somebody forgot the variable fails safe instead of showing error pages full of internals. A missing SECRET_KEY raises an error at start up, which is exactly what you want.
Aisling's .env (in .gitignore):
DEBUG=on
SECRET_KEY=only-for-this-laptop
ALLOWED_HOSTS=localhost,127.0.0.1
DATABASE_URL=postgres://priya@localhost:5432/freewheel_development
And the committed .env.example, so Cian knows what to fill in:
DEBUG=on
SECRET_KEY=
ALLOWED_HOSTS=localhost,127.0.0.1
DATABASE_URL=postgres://USER@localhost:5432/freewheel_development
The custom user model, before the first migrate
This is the decision this chapter exists for, and the one most often missed.
Django ships a complete authentication system: a User model, password hashing, login and logout views, permissions, groups, the admin. That is one of Django's real strengths, and the reason this decision comes up at all. Rails 7.1 gives you building blocks such as has_secure_password and authenticate_by, but no user model, so in Rails you design your own users from the start anyway2. Django gives you a finished one, and the question is whether to use it as it is.
The Django documentation is unusually direct: if you are starting a new project, it is highly recommended to set up a custom user model, even if the default one is sufficient for you12. The custom model behaves exactly like the built in one. The point is that it belongs to you, so you can change it later.
Why it is so hard to change later
Every model that refers to a user, a mechanic's login, a job card's "last changed by", an audit log, has a foreign key to the user table. Django's own apps do too: admin log entries, user permissions, group memberships. All of those foreign keys are written into migrations at the moment they are created, pointing at whichever model AUTH_USER_MODEL named at that time.
The setting is what Django calls swappable: you may swap the user model, but only once, at the start. The documentation spells out why. Changing AUTH_USER_MODEL after database tables exist is significantly more difficult because it affects foreign keys and many to many relationships. It cannot be done automatically, and requires fixing the schema by hand, moving data from the old user table and possibly reapplying some migrations12. The model must also be created in the first migration of its app, or you run into dependency problems. The steps are outlined in Django ticket 25313, opened in 2015, whose title tells you everything: document how to migrate from a built in user model to a custom one16.
In the pencil, pen and ink model, the user model is the darkest ink there is. It is in the first migration, in every foreign key, and in every row that refers to a person.
The cost of doing it right on day one is about ten lines of code. The cost of doing it on month six is days of careful work on a live database. That asymmetry is the whole argument.
Example: Freewheel's user model in code
Aisling creates an accounts app for everything about logging in, and the other apps from the structure chapter:
django-admin startproject freewheel .
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
The user model, in accounts/models.py:
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
"""Everyone who logs in to Freewheel: managers, mechanics, front desk.
Empty on purpose. It behaves exactly like Django's built in user,
but it is ours, so adding a field later is an ordinary migration.
"""
It is empty, and that is correct. AbstractUser brings username, names, email, password, staff and active flags and permissions, everything the built in model has.
Register it with the admin, in accounts/admin.py, as the documentation shows:
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import User
admin.site.register(User, UserAdmin)
Point the setting at it, in settings.py, together with the apps:
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
# Freewheel's own apps
"accounts",
"workshops",
"bookings",
"repairs",
"parts",
]
# The one line that must exist before the first migrate
AUTH_USER_MODEL = "accounts.User"
Only now does Aisling run the first migrations:
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser
makemigrations writes accounts/migrations/0001_initial.py with the User model in it, which is exactly the "first migration of its app" the documentation asks for.
Every other model refers to users through the setting, never through a class. That keeps the code correct whatever the user model is. Here is the mechanic, in workshops/models.py:
from django.conf import settings
from django.db import models
class Workshop(models.Model):
name = models.CharField(max_length=100)
city = models.CharField(max_length=100, default="Limerick")
def __str__(self):
return self.name
class Mechanic(models.Model):
# Point at the setting, never at a concrete User class
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
workshop = models.ForeignKey(Workshop, on_delete=models.PROTECT, related_name="mechanics")
def __str__(self):
return self.user.get_full_name() or self.user.username
In code that runs at request time, such as a test or a view, use get_user_model() to get the class. Both are the patterns the documentation recommends12.
Six months later, when Niamh asks for a mechanic's preferred workshop on the login itself, the change is one field and one ordinary migration. That is "additions, not replacements" in practice.
Customers are not users, yet
A second ink question hides behind the first: who logs in? In version one of Freewheel, managers, mechanics and the front desk log in. Customers do not: they book online with their name, email and phone, and get a link by email. So customers are a separate model, not users.
This keeps the user table small and the permission story simple. If Freewheel later wants customer accounts, the change is again an addition: a nullable one to one link from Customer to the user model. Merging two tables later would be a replacement, and that is the expensive kind. The Django series picks up logins, permissions and security in its chapter on authentication.
Time zones: store UTC, show local
A time zone bug is the kind that waits. Everything looks right in testing, and then the clocks change.
With USE_TZ = True, Django works with time zone aware datetimes, stores them in UTC in the database, and converts them to the current time zone (by default the TIME_ZONE setting) in templates and forms17. Since Django 5.0 this is the default1.
Here is the interesting part, and it moves this decision out of ink. The Django documentation says that on PostgreSQL, which stores datetimes as timestamp with time zone, you can switch between USE_TZ = False and USE_TZ = True freely, with no data conversion. On other databases, switching means converting stored local times to UTC, which is not deterministic around daylight saving changes17. So on PostgreSQL the stored data is safe either way. What is not safe is the code: every place that builds a datetime without a time zone (a "naive" datetime) has to be found and fixed. That is pen, spread through the codebase, and it grows with every feature. Keep USE_TZ = True from the start and the problem never arises.
Example: 9am stays 9am across the clock change
Irish clocks go forward by one hour at 1am on the last Sunday in March, the same moment as across the EU18. In 2024 that was Sunday 31 March, two days before this article. Freewheel takes about 30% of its week's online bookings between Friday 6pm and Saturday noon, so in an average week that is:
where is the number of bookings arriving in the Friday evening to Saturday noon window, is the peak share of the week's online bookings and is the bookings per week. The arithmetic of shares is in Foundations: percentages.
If the booking times were stored as naive local times and later read as UTC, every one of those 345 bookings made for the weekend of 6 April would show an hour late on the workshop board. Aisling writes a test that pins the behaviour down. Freewheel's settings:
LANGUAGE_CODE = "en-ie"
TIME_ZONE = "Europe/Dublin" # what people see
USE_I18N = True
USE_TZ = True # what the database stores: UTC
A minimal booking model, in bookings/models.py (the full model follows in the identifiers section):
class Booking(models.Model):
workshop = models.ForeignKey(Workshop, on_delete=models.PROTECT)
mechanic = models.ForeignKey(Mechanic, on_delete=models.PROTECT)
bike = models.ForeignKey(Bike, on_delete=models.PROTECT)
starts_at = models.DateTimeField() # stored in UTC because USE_TZ = True
And the test, in bookings/tests.py:
from datetime import datetime
from zoneinfo import ZoneInfo
from django.utils import timezone
DUBLIN = ZoneInfo("Europe/Dublin")
def test_nine_am_stays_nine_am_across_the_clock_change(self):
before = self.book(datetime(2024, 3, 30, 9, 0, tzinfo=DUBLIN)) # GMT, winter time
after = self.book(datetime(2024, 4, 6, 9, 0, tzinfo=DUBLIN)) # IST, summer time
before.refresh_from_db()
after.refresh_from_db()
# Stored in UTC: one hour apart in the database ...
self.assertEqual(before.starts_at.hour, 9)
self.assertEqual(after.starts_at.hour, 8)
# ... and both 9am on the workshop clock
self.assertEqual(timezone.localtime(before.starts_at).hour, 9)
self.assertEqual(timezone.localtime(after.starts_at).hour, 9)
The test method sits in a TestCase class whose setUp creates a workshop, a mechanic, a customer and a bike, and whose helper book creates a booking at the given time. Saturday 30 March is on winter time, Greenwich Mean Time, so 9am is 09:00 UTC. Saturday 6 April is on Irish Standard Time, the summer time, so 9am is 08:00 UTC. The database holds two different UTC hours, the board shows 9am both times. Nobody on the shop floor has to think about it again.
Money: Decimal, and the rounding rule in one place
Never store money as a floating point number. Floats are binary fractions, and most decimal amounts, such as 0.10, cannot be stored exactly. Python's documentation of the decimal module explains the effect and why Decimal exists: exact decimal arithmetic with rounding under your control19. Django's DecimalField is a fixed precision decimal number, represented in Python by a Decimal, and the field reference points to the difference from FloatField explicitly20.
This is ink: the column type and every stored amount. It is also an area where the two frameworks' communities tend to differ. The Rails chapter discusses integer cents and the money gem, an approach many Rails applications take. In Django, DecimalField with Python's Decimal is the usual path, and it works well, as long as you also decide one more thing: the rounding rule.
For an invoice with VAT, the calculation is:
where is the net amount, is the VAT rate as a fraction, rounds to the nearest cent with an explicit rule (here half up), is the VAT and is the gross amount. Percentages as fractions are explained in Foundations: percentages.
Whether you round each invoice line or the invoice total, and which way, is a question for your accountant, not for the framework. The code's job is to make the answer explicit and keep it in one place. This is general information, not tax or legal advice.
Example: the invoice and the hundred chains
A typical Freewheel repair: one and a half hours of labour at €52 an hour, a new chain at €18.99 and two brake pads at €7.49 each. The standard VAT rate in Ireland, as published by Revenue, is 23%21.
The net amount, the VAT rounded to the cent, and the gross:
where , and are the net, VAT and gross amounts in euro, is the hours of labour, the hourly labour rate and the VAT rate (Foundations: percentages). So the invoice says €111.97 net, €25.75 VAT, €137.72 to pay.
In code, the part's price is a DecimalField, in parts/models.py:
from django.db import models
class Part(models.Model):
name = models.CharField(max_length=200)
sku = models.CharField(max_length=50, unique=True)
# Money is Decimal, never float: up to 999,999.99 to the cent
unit_price = models.DecimalField(max_digits=8, decimal_places=2)
in_stock = models.PositiveIntegerField(default=0)
The rounding rule lives in one small function, in parts/money.py:
from decimal import ROUND_HALF_UP, Decimal
IE_STANDARD_RATE = Decimal("0.23")
CENT = Decimal("0.01")
def vat_for(net: Decimal, rate: Decimal = IE_STANDARD_RATE) -> Decimal:
"""VAT on a net amount, rounded to the cent, half up.
The rounding rule is a business decision: agree it with your accountant
and write it down here, in one place.
"""
return (net * rate).quantize(CENT, rounding=ROUND_HALF_UP)
And two tests pin both the rule and the reason for Decimal, in parts/tests.py:
from decimal import Decimal
from django.test import SimpleTestCase
from .money import vat_for
class VatTest(SimpleTestCase):
def test_vat_on_the_example_invoice(self):
net = Decimal("78.00") + Decimal("18.99") + Decimal("7.49") * 2
self.assertEqual(net, Decimal("111.97"))
self.assertEqual(vat_for(net), Decimal("25.75"))
self.assertEqual(net + vat_for(net), Decimal("137.72"))
def test_a_hundred_chains_add_up_to_the_cent(self):
self.assertEqual(sum([Decimal("18.99")] * 100), Decimal("1899.00"))
self.assertNotEqual(sum([18.99] * 100), 1899.0) # the float trap
The second test documents the trap. Freewheel's nightly parts report adds up what was used. A hundred chains at €18.99, added as floats in Python 3.12, come to 1898.9999999999998, not 1899.0. Rounded for display it looks grand. Compared with the payment provider's total, it does not match, and someone spends an afternoon hunting for a cent that never existed, and giving out about it. With Decimal the sum is exactly 1899.00.
Identifiers: keep the integer key, add a UUID where the outside world sees it
Every Django model gets a primary key. With the generated settings it is a BigAutoField, a 64 bit integer that counts up22. The alternative people ask about is a universally unique identifier (UUID), a 128 bit value that is practically impossible to guess. Django's UUIDField stores it in PostgreSQL's native uuid type, and the documentation notes that the database does not generate the value for you, so you pass default=uuid.uuid420.
Changing the primary key type of a table later is ink: every foreign key pointing at it changes too. The settings reference even warns that the primary keys of existing automatically created many to many tables cannot be updated by the migrations framework at all22.
My view: keep integer primary keys inside the database, where they are small, fast to index and easy to read in a debugging session. Add a separate UUID column where an identifier leaves the building: a link in an email, a URL a customer can see, a reference a mechanic's app will hold. Counting integers in public URLs tell anyone how many bookings you take and invite people to try the next number. That leaves the expensive decision (the primary key type) at its safe default, and turns the public reference into an addition you can make per model.
Example: the booking reference in the "your bike is ready" link
Freewheel emails customers when their bike is ready, with a link to the job card. The link uses the booking's reference, never its id. The full booking model, in bookings/models.py:
import uuid
from django.db import models
from workshops.models import Mechanic, Workshop
class Customer(models.Model):
# Customers book without a password in version one, so they are not users
name = models.CharField(max_length=200)
email = models.EmailField()
phone = models.CharField(max_length=30, blank=True)
class Bike(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name="bikes")
description = models.CharField(max_length=200) # "Blue gravel bike"
class Booking(models.Model):
# Internal key stays a fast BigAutoField; the public reference is a UUID
reference = models.UUIDField(default=uuid.uuid4, unique=True, editable=False)
workshop = models.ForeignKey(Workshop, on_delete=models.PROTECT)
mechanic = models.ForeignKey(Mechanic, on_delete=models.PROTECT)
bike = models.ForeignKey(Bike, on_delete=models.PROTECT)
starts_at = models.DateTimeField() # stored in UTC because USE_TZ = True
created_at = models.DateTimeField(auto_now_add=True)
The link in the email becomes https://freewheelcycles.example/bookings/3f2b.../ instead of /bookings/48211/. Once those emails are in 9,000 customers' inboxes, the reference format is ink in a place no migration can reach. That is why the decision belongs before the first email, not after.
While she is at it, Aisling adds the job card with its four statuses, in repairs/models.py. Django 5.0 accepts the choices class directly1:
from django.db import models
from bookings.models import Booking
class JobCard(models.Model):
class Status(models.TextChoices):
WAITING = "waiting", "Waiting"
IN_REPAIR = "in_repair", "In repair"
READY = "ready", "Ready"
COLLECTED = "collected", "Collected"
booking = models.OneToOneField(Booking, on_delete=models.PROTECT, related_name="job_card")
# Django 5.0 accepts the choices class directly, no .choices needed
status = models.CharField(max_length=20, choices=Status, default=Status.WAITING)
The status values (waiting, in_repair, ready, collected) are stored strings, so they are ink too. The labels people see are pencil and can change any time. The next chapter, on the Django ORM, builds out the rest of the schema.
Static files with WhiteNoise
Static files are your CSS, JavaScript and images. In development, runserver serves them. In production, Django does not serve them itself, and the documentation describes the options: a separate web server, a content delivery network, or cloud storage23.
WhiteNoise, by David Evans, is a small package that lets the Python application serve its own static files efficiently, with compression and long cache headers, without a separate server24. For an application of Freewheel's size it removes one moving part from the first deploy. This is pencil: if Freewheel ever moves its static files to a content delivery network, that is a settings change.
Example: three settings and one line of middleware
Following the WhiteNoise 6.6 documentation for Django 4.2 and later24:
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"whitenoise.middleware.WhiteNoiseMiddleware", # straight after security
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]
STATIC_URL = "static/"
STATIC_ROOT = BASE_DIR / "staticfiles"
STORAGES = {
"default": {"BACKEND": "django.core.files.storage.FileSystemStorage"},
"staticfiles": {
"BACKEND": "whitenoise.storage.CompressedManifestStaticFilesStorage",
},
}
One detail that catches people: the STORAGES setting replaces Django's default dictionary as a whole, so if you set it you must keep the default entry for uploaded files as well. The before and after photos on job cards will need that entry, and the Django series covers file uploads in its chapter on background tasks, email and files.
The front end: templates and htmx, or an API
This is the biggest pen decision, and the one where the team's backgrounds pull hardest.
Django renders HTML with its template language out of the box. With htmx (version 1.9 at the time of writing25), a small JavaScript library, HTML elements can fetch fresh fragments from the server and swap them into the page, which covers live updates like a workshop board without writing a separate JavaScript application. The other route is an API, typically with Django REST Framework, behind a React, Vue or Svelte front end.
Both are legitimate, and a later chapter of this series compares them in depth: Django templates, htmx or an API, choosing the front end. For the start, two things matter. It is pen, not ink: no migration depends on it, but every view and template does. And an API added later, alongside server rendered pages, is an addition. Rebuilding a finished React front end as server rendered pages, or the reverse, is a replacement.
The Rails side of the same question is in Hotwire in Rails. htmx is the closest Django equivalent to Turbo, though the two differ in how much they do by convention.
Example: Cian's React instinct
Cian's first instinct is a React front end. It is what he knows best. Aisling and Cian list what Freewheel's first version needs on screen: a booking form, the workshop board, job cards, a manager's back office. The back office is covered for a start by the Django admin, which the series explores in its own chapter. The board needs live updates, which htmx handles with polling or server sent events. Nothing in version one needs a separate JavaScript application.
The mechanics' mobile app, planned for later, will need an API. Because an API can be added beside the templates when that day comes, they choose templates and htmx for version one. Cian's React experience is not wasted: the mental model of components maps well onto Django's template includes, and he will lead the API when the app arrives.
The first hour, side by side
Both frameworks get you to a running application with a database in about an hour. They get there differently, and the differences are useful to know if you are comparing them, as Freewheel did.
| Step | Rails 7.1 | Django 5.0 |
|---|---|---|
| Runtime | Ruby through a version manager (rbenv, asdf, chruby) | Python 3.12 plus a virtual environment |
| Create | rails new freewheel --database=postgresql | django-admin startproject freewheel . |
| Choices on day one | Flags on the command line | Defaults in settings.py, read and edited |
| Database | Chosen by flag, config/database.yml | SQLite by default, change DATABASES |
| Users | No user model generated, building blocks available | Complete auth.User, swap for a custom model before migrate |
| First feature | bin/rails generate scaffold writes model, views, routes and tests | startapp, then write the model, register it in the admin |
| Back office | None built in | The Django admin |
| Run locally | bin/dev | python manage.py runserver |
| Tests | Minitest, and scaffold generates system tests | Python's unittest through manage.py test, pytest optional |
| Container | Dockerfile generated by default | Written by hand |
Sources for the Rails column are the Rails 7.1 release notes and command line guide226, for the Django column the Django 5.0 documentation327. Neither column is better. Rails generates more and expects you to follow its conventions. Django generates less and gives you the admin and a full authentication system in return. The testing series later in this programme covers both toolchains in depth.
From empty folder to first deploy
Here is the whole path for Freewheel, from the empty folder to a first deploy, with the ink decisions where they belong.
Example: Freewheel's first deploy checklist
Before the first deploy, Aisling runs Django's own deployment check with production settings13:
DEBUG=off SECRET_KEY="$(python -c 'from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())')" \
python manage.py check --deploy
On the settings so far it warns about missing HTTPS settings. She adds a production block at the end of settings.py:
if not DEBUG:
# Production only: HTTPS everywhere, secure cookies
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_HSTS_SECONDS = 3600 # one hour first; raise it once HTTPS is proven
Run again, check --deploy leaves two warnings: one about including subdomains in HTTP Strict Transport Security (HSTS) and one about the browser preload list. Both are deliberate choices to make once HTTPS is proven on every subdomain, which is why the documentation leaves them to you.
The release steps themselves, on whatever host Freewheel picks (a platform service or a container, compared in Django vs Rails in production):
pip-sync requirements.txt # exactly the pinned packages
python manage.py collectstatic --noinput # gather static files for WhiteNoise
python manage.py migrate # apply migrations to production
gunicorn freewheel.wsgi # start the application server
Gunicorn is one of the application servers the Django documentation describes for production28. The environment on the host holds SECRET_KEY, ALLOWED_HOSTS (freewheelcycles.example) and DATABASE_URL, and nothing secret is in Git.
Decisions and their reversal cost
Here is the full table for Freewheel, with the layer, when to decide and my estimate of what reversing the decision would cost at month six.
| Decision | Layer | Decide before | Freewheel's choice | Reversal at month six (my estimate) |
|---|---|---|---|---|
| Custom user model | Ink | first migrate | accounts.User from AbstractUser | 8 developer days, careful data migration |
| Primary key type | Ink | first migrate | BigAutoField | 5 days |
| Database engine | Ink | first real data | PostgreSQL | 4 days |
| Money type | Ink | first price | DecimalField, one rounding function | 3 days |
| Public references | Ink | first email | UUID column on bookings | 2 days, and old links break |
| Time zones | Pen | first booking | USE_TZ = True, Europe/Dublin | 2 days on PostgreSQL |
| Front end approach | Pen | first feature | Templates and htmx | 20 days |
| Dependency tool | Pencil | first teammate | pip with pip tools | half a day |
| Settings source | Pencil | first deploy | django environ, .env locally | 1 day |
| Static files | Pencil | first deploy | WhiteNoise | half a day |
The estimates are my judgement for an application of Freewheel's size after six months of work, not measurements. Treat them as orders of magnitude.
The chart holds one surprise worth naming. The single most expensive decision to reverse is pen, not ink: the front end approach, because it touches every screen. It is still pen, because no data has to move, and it can be postponed until the first feature. The custom user model costs fewer days to reverse, but it cannot be postponed past the first migrate at all, and it is the decision most often forgotten. That is the difference between expensive and urgent, and the pencil, pen and ink model is how you keep the two apart.
For the person paying for this
If you commission a Django application, you do not need to read the code to check the start was sound. Ask for five things in the first week:
- Show me the custom user model. There should be an
AUTH_USER_MODELsetting and a user model in the project's own code, created in the first migration. If the answer is that the project uses the built in one, ask why, and ask what it would cost to change in a year. - Show me where money is. Prices and totals should be
DecimalField, and the rounding rule should be written down in one place, agreed with your accountant. - Show me that no secret is in Git. There should be an example environment file with empty values, and the real values only on the server.
- Show me the output of
manage.py check --deploy. Every remaining warning should have a reason. - Show me the pinned dependencies and the Django version plan. Which version, supported until when, and when is the next upgrade?
Good developers will be glad you asked. None of the five takes more than ten minutes to show.
If you are still deciding which framework to build on, the method is in how to choose between Django and Rails. I build web applications on Ruby on Rails, not Django, and say so openly. If Rails is where you land, my web application development page shows how I work, and my prices are published.
My view
What the documentation says: use a custom user model when starting a project, keep the secret key out of the code, run the deployment check, and use DecimalField for money. What the community adds, in the form of Cookiecutter Django's defaults: environment based settings, PostgreSQL everywhere, a custom user from the first commit. Where they agree, they are right, and Freewheel follows both.
My own judgement adds two things. First, sort decisions by where they get written down, and spend your first day only on the ink. Second, in Django the danger at the start is not a wrong choice but an unnoticed one, because startproject decides quietly. Read every line of the generated settings once, on day one, and decide each one on purpose. It takes an hour, and it is the best hour of the project.
Conclusion
A new Django project starts in a minute and a good one starts in a day. The difference is the handful of decisions that get written into migrations and data: the custom user model, the primary key type, money as Decimal, the database engine and the public identifiers. Make those before the first migrate. Make the front end choice before the first feature. Leave the dependency tool, the settings library and static files as sensible defaults and revisit them before the first deploy.
Freewheel's Django spike now has a project, five apps, a user model it owns, money that adds up to the cent and bookings that stay at 9am when the clocks change. The next chapter builds the rest of the schema with the Django ORM, and makes sure it stays fast as the bookings grow.
