ContentsClose contents
Pre-release
Chapter 7 · Django apps and application boundariesCHAPTER 07

Six-part pre-release for review, with seven figures and nine tables. The installed, empty events app remains the chapter's checkpoint; content approval is open.

Working towards: First Otahque page (Chapter 9). Django answers a request with a page written for Otahque. All milestones

CHAPTER SEVEN

Django apps and application boundaries

Stage 1: Requirements and first project (Chapters 1 to 8)

Prerequisites: Chapters 4 to 6, and the verified Chapter 6 project with a passing system check

What you’ll build: an installed, empty events app in the Otahque project, and a short record of why its boundary was chosen.

Why This Matters

Chapter 6 gave us a project that answers a browser, but it contains no Otahque behaviour yet. Very soon Sam will want an event page, Sai a confirmed place, and Raj a way to cancel. All of that code has to live somewhere, and where it lives is a decision we will feel for the rest of the book.

Django organizes a project’s features into apps. If we create apps first and think later, the folders end up reflecting the order in which we happened to write things, and every later change crosses several of them. Where a model lives also matters more than it first appears: by default, Django names a model’s database table after its app, so moving a model after migrations exist needs a careful plan for migration state and stored data, not a rewrite of migrations already applied. A little design now saves that work later.

So this chapter does three things in order. It looks at the apps our project already uses, so that “app” means something concrete. It uses Otahque’s requirements to propose which apps we need and which one to create first. Then it creates that app, installs it, and proves that Django has loaded it, rather than assuming so.

By the end of the chapter, you will be able to:

  • explain what a Django app is and how it differs from a project and from an ordinary Python package;
  • identify the apps a project installs and what each one supplies;
  • propose app boundaries from Otahque’s requirements and explain the trade-offs;
  • generate an app and explain the job of each generated file;
  • install an app and confirm that Django has loaded it;
  • diagnose common app-creation and installation problems without overwriting your work.

Migrations stay unapplied throughout this chapter. Routes and views begin in Chapters 9 and 10, the first model in Chapter 16, and dependency locking and Git in Chapter 8.

PAGE 001

What You Need to Know

An app supplies a capability

New Concept: Django app

What problem exists? A website does many unrelated things: it signs people in, remembers them between requests, shows events, and records registrations. Kept in one place, that code becomes a pile in which every change risks something unrelated.

What did people do before? Projects often grouped code by technical layer: all the pages in one folder and all the database code in another. That spread one feature across several folders.

What is a Django app? A Python package that supplies one related set of website features, a capability. It can bring any of the pieces we traced in Chapter 5 for that capability, such as views, models, and templates, together with related files such as static files, administration settings, and tests. It does not need all of them.

Why apps? Django finds an installed app’s models, templates, and other files automatically, so each capability can be read, tested, and reused as a unit. Django’s own features, from accounts to sessions, are shipped as apps in exactly this way.

Now let’s look at the ones we already have.

The project is the assembly. Its settings say which apps take part, and its root URL configuration connects the addresses this project exposes to views or to other URL configurations. Django learns which apps are installed from one setting, INSTALLED_APPS. A package that is not listed there is still ordinary Python code that can be imported. Django simply does not register it as an installed app, so it does not look inside it for the files it finds automatically.

The apps your project already has

It is tempting to think that our project has no apps because we have not created one. In fact, the project generated in Chapter 6 already uses six. Open config/settings.py in your editor and find the assignment that begins with INSTALLED_APPS. This step only reads the file; change nothing. In a freshly generated Django 6.1.2 project, it looks like this:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

From Chapter 4, you can read this as a Python list of strings. Each string is a dotted path, the same form we use after import. django.contrib is a package inside Django that holds optional apps shipped with the framework, and the generated project switches these six on by default. Table 7.1 shows what each supplies and where the book develops it.

Table 7.1 — The apps that startproject installed
App What it supplies Where we use it
admin A staff administration site for managing records. Chapter 23
auth User accounts, groups, permissions, and password checks. Chapters 17, 27, and 30
contenttypes A record of which models exist, used by permissions and the administration site. Chapter 30
sessions A way to remember a browser between requests. Chapters 27 and 28
messages One-time notices shown after an action. Chapter 28
staticfiles Finding and serving CSS, images, and scripts during development. Chapter 13

If your list differs, do not edit it now. A difference means the file is not the one generated in Chapter 6, or it has since changed. Compare it with a fresh copy, as described in Chapter 6, How We Build It, “Compare with a fresh copy when needed”, before continuing.

Que. 1 Chapter 6, How We Build It, shortened the runserver output in the server-starting step. The full migration warning names the apps with unapplied migrations: admin, auth, contenttypes, and sessions. Why are messages and staticfiles not named?

Flip to check your answerFold answer back

Answer. In this generated project, admin, auth, contenttypes, and sessions include database models and shipped migrations that have not yet been applied. messages and staticfiles have no tables or migrations of their own. An app can supply a capability without owning database tables.

A project, an app, and a package are different things

Three words can describe the same folder, so it helps to separate them. A Python package is a directory of importable modules; config/ became one through its __init__.py file. A Django app is a Python package that supplies related website features. An installed app is one that this project registers through INSTALLED_APPS. A Django project is the configuration that brings apps together, chiefly its settings. Figure 7.1 shows the relationship.

The INSTALLED_APPS setting in config/settings.py points to the group of installed apps Django registers: admin, auth, contenttypes, sessions, messages, and staticfiles, with a dashed place for Otahque’s own events app. Below, a plain Python package that is not listed is not an installed app, although Python can still import it.
Figure 7.1 — The settings list decides which packages Django registers as installed apps.

Being importable is not the same as being installed. Python can import a package from the work folder whether or not it is listed. Only a listed package becomes an installed app, so Django includes it when it looks for models, templates, and other app files. The config/ package holds the project’s configuration and is not in the list.

Que. 2 config/ is a Python package in the project folder. Is it a Django app?

Flip to check your answerFold answer back

Answer. No. It is importable because it contains __init__.py, but it does not appear in INSTALLED_APPS. Its job is project configuration: settings, the root URL configuration, and the server interfaces. Django does not treat it as an app or look in it for models.

How Django loads installed apps

Each time a management command or the development server starts, Django reads the settings and loads the listed apps in order. Because loading happens at startup, a change to INSTALLED_APPS affects the next command or server start. During development, runserver usually reloads when a Python file changes; if you are unsure whether a running server has seen a change, stop it and start it again.

Under the Hood: How Django builds the app registry

At startup, django.setup() calls the registry’s populate() method in django/apps/registry.py with your INSTALLED_APPS. It works in three phases. Phase 1 imports each entry and creates its configuration object with AppConfig.create(); every app’s label must be unique, so a repeated label stops loading with ImproperlyConfigured. Phase 2 imports each app’s models module, if it has one. Phase 3 calls each configuration’s ready() method, then marks the registry ready. Model lookup becomes available after phase 2, and ready() may import model classes. Keep model imports out of apps.py at module level, and avoid database queries during initialization.

Later in this chapter, Figure 7.3 draws these phases once our own app takes part. For now, remember the order: import and configure, then models, then start-up code.

In practice: reading an unfamiliar project

Situation. A new contributor joins Otahque later and needs to understand what the project depends on before changing it.

Application. INSTALLED_APPS is a fast first map. It shows which capabilities Django will load, which came with Django, and which belong to the project. The same habit helps when a guide suggests adding a package: check whether it is an app that needs listing, and what capability it adds.

Consideration. The list shows what is loaded, not how each app is used or whether it is configured well. Treat it as a starting point for reading the code, not as a review.

Try it yourself

Using Table 7.1, decide which installed app is most directly involved in each future need. Sai registers for the workshop and sees a one-time notice saying her place is confirmed. Soni signs in and stays signed in as she moves between pages. Sam’s event page loads its stylesheet during development. Then say whether listing these apps alone finishes the configuration of those features.

Que. 3 Which app supports each need, and does listing the apps finish the job?

Flip to check your answerFold answer back

Answer. The one-time notice comes from messages. Staying signed in combines auth, which knows the account, with sessions, which remembers the browser between requests. The stylesheet during development comes from staticfiles. Listing the apps does not finish the job on its own: INSTALLED_APPS registers each app, but its feature may also need middleware, template settings, or other wiring. Our generated project already includes the usual supporting settings, and we explain them as each feature is implemented. None of these apps enforces Otahque’s rules, such as who may register.

Drawing Otahque’s first app boundaries

A boundary is the line between what one app looks after and what belongs to another. Three questions help us draw it:

  • Responsibility: which part of the product does this app answer for? Name it in one short phrase, such as “what is offered”.
  • Data ownership: which stored records does it define and keep correct? From Chapter 16, an app’s models describe those records.
  • Dependency direction: which other apps does it need to refer to, and which should never need to refer back to it?

These questions come from the product, not from the pages. A page often shows information owned by several apps. Sai’s registration page shows an event and her place in it, but that does not make the page an app. An app is not a single page, a URL prefix, or a layer such as “all the views”.

Chapter 2’s requirements give us the material. PR-1 to PR-3 concern places: one confirmed place per eligible registration, cancellation that releases a place, and capacity that holds when two people compete. PR-4 concerns who may see and change what. Underneath them sit three kinds of record: events, the people who use Otahque, and the registrations that connect people to events. Table 7.2 turns those records into candidate apps. Read it as a proposal for review, not as an accepted design.

Table 7.2 — Proposed first app boundaries for Otahque
App Responsibility Records it will own Created in
events What is offered: event details, timing, capacity, and publication. Events (first model in Chapter 16). This chapter
accounts Who people are: the user model and signing in. The custom user (Chapter 17). Chapter 17
registrations Who holds a place: registering, cancelling, and capacity checks (pages in Chapter 31). Registrations linking a member to an event. Chapter 20
Three app boxes. events, created now, holds event details, timing, capacity, and publication. accounts, dashed and planned for Chapter 17, holds the user model and signing in. registrations, dashed and planned for Chapter 20, holds registering, cancelling, and capacity checks. An arrow labelled organizer runs from events to accounts, and arrows labelled refers to run from registrations up to events and to accounts.
Figure 7.2 — Proposed boundaries: one app now, two when their chapters need them.

The arrows show dependency direction. A registration refers to one event and one member, so registrations depends on both. An event refers to its organizer, so events depends on accounts. These proposed record references do not require a reverse reference from an event or account to a registration. The arrows record which records refer to which; some operations still need information across a boundary. Reducing an event’s capacity, for example, needs the current registration count, which should be obtained deliberately rather than by reversing the arrow.

All three apps live in one project and run as one application. Chapter 5’s proposed ADR-001 chose a single server-rendered Django application. Apps divide the code inside it; they are not separate services.

Que. 4 Why is registrations proposed as its own app rather than part of events?

Flip to check your answerFold answer back

Answer. They answer for different things and own different records. Events describe what is offered. A registration connects a member to an event and carries the rules in PR-1 to PR-3. Keeping them apart lets the events app make sense on its own, while registrations depends on events and accounts. Both are still part of the same project and the same running application.

Too few apps, or too many

Both extremes are common. One large app holding everything works for a tiny project but turns into a pile of unrelated code: event rules, sign-in, and capacity checks side by side. The opposite mistake creates an app for each page or small feature, such as event_list, event_detail, and cancel_button. Those apps share the same records, so every change crosses several of them.

Where a model lives matters later. Django uses the app label in each model’s default database table name. By default, a model named Event in the events app is stored in a table called events_event, and the app’s migration history records it there. Moving a model to another app after migrations exist requires a plan for migration state, table names, and stored data as well as the code; do not rewrite already-applied migrations. So we choose boundaries before writing the first model, and we keep the first choice small.

Que. 5 Someone suggests one app per page: event_list, event_detail, and registration_form. What is the main problem?

Flip to check your answerFold answer back

Answer. Those pages all work with the same event and registration records, so the responsibility is split by screen rather than by what the code answers for. Every rule change would touch several apps, and it would be unclear which app owns the records and keeps them correct. A page belongs inside the app that owns its main responsibility, or is decided separately, as the home page will be in Chapter 9.

Prefer creating all three apps now?

Empty apps cost little to generate, so creating accounts and registrations today is tempting. We do not, because they would add names and settings that nothing uses yet, and an early guess may change once we reach those chapters. We create events now, because the next chapters build event pages and the first model. accounts follows in Chapter 17, which chooses the user model before the first migration is applied, and registrations in Chapter 20, with its first model. Where the home page lives is decided in Chapter 9.

Table 7.3 records the decision in the same shape as Chapter 5’s architecture record. It is the “short record of why” promised at the start of the chapter.

Table 7.3 — Boundary decision record (proposed)
Field Content
Status Proposed, October 2026. Not yet reviewed or accepted.
Decision Create one app, events, now. Create accounts in Chapter 17 and registrations in Chapter 20.
Reason Each app owns one responsibility and its records. The next chapters need events only. Model locations are hard to change after migrations, so we decide before the first model.
Consequences One installed app of our own in this chapter. Later chapters add apps instead of moving code between them.
Revisit if A responsibility does not fit any app, or one app starts owning unrelated records.

In practice: placing a later feature

Situation. In Chapter 46, Otahque gains a waitlist that offers released places to the next member in line.

Application. Ask the three questions before writing code. A waitlist place connects a member to an event and depends on capacity, which suggests registrations as its owner rather than a new app.

Consideration. The answer is a proposal for that chapter to confirm. A boundary table records today’s reasoning; it does not settle future decisions automatically.

Try it yourself

Using Table 7.2, propose an owning app for three future needs: Sam sees the list of people registered for his event; Soni resets a forgotten password; and an organizer’s event becomes visible to members when it is published. For each, name the records involved and the app that owns them. Write your proposals before reading the answer.

Que. 6 Which app should own each need?

Flip to check your answerFold answer back

Answer. Sam’s attendee list reads registrations for one event, so registrations owns it; the page may appear in organizer screens, but the records belong to registrations. Resetting a password concerns a person’s account, so it belongs to accounts, building on Django’s auth app. Publication is part of an event’s own state, so events owns it. Each answer follows the owner of the records, not the page where the result appears.

PAGE 002

How We Build It

Starting point: the verified Chapter 6 project, with the boundary decision from Table 7.3. Work in otahque/, the folder that contains manage.py and .venv/. These steps create an events/ package beside config/ and change one line of config/settings.py. The visible result is a passing check events command and a registry lookup that prints the app’s configuration.

The Custom Way: an app by hand

Before we let Django generate anything, it helps to see how little an app needs. Read this listing; do not create these files. An app can be just a package with a configuration class:

events/
    __init__.py      (empty: marks events/ as a package)
    apps.py
from django.apps import AppConfig


class EventsConfig(AppConfig):
    name = 'events'

Listed in INSTALLED_APPS, those two files are already a working, if empty, app. Writing them by hand for every app is error-prone, though: a misspelled class name or a missing __init__.py produces confusing errors, and each later chapter would need its own placeholder files. That is what Django’s generator saves us.

The Django Way: startapp

Step 1: Choose a name Django will accept

The app name becomes a Python package name, so it must be a valid identifier: letters, digits, and underscores, not starting with a digit. event-pages is refused because a hyphen cannot appear in a Python name. The name must also not clash with a module Python can already import. email and calendar are part of Python’s standard library, so Django refuses both. In each case, Django creates nothing.

We use events: it is a valid identifier, it does not clash with an installed module, and it names the responsibility in Table 7.2. By convention, app names are short, lowercase, and often plural. The name also becomes the app’s label, which appears in default table names such as events_event, so choose it once.

Common Error: a name that conflicts with an existing module

If you see CommandError saying the name conflicts with the name of an existing Python module, nothing was created. Choose another name. The same message appears if you run startapp events a second time, because events is then importable; inspect the existing folder instead of regenerating it.

Que. 7 Why does Django refuse calendar but accept events?

Flip to check your answerFold answer back

Answer. calendar is already importable as a module in Python’s standard library. If our app used that name, imports of calendar could find the wrong package, so Django refuses it before creating any files. events is a valid identifier that no installed module uses, so Django can create it.

Step 2: Generate the app beside manage.py

The startapp management command creates the app in the current folder. Run it through manage.py from otahque/, so the new package sits beside config/ and manage.py, where Python and Django will look for it.

PowerShell, in otahque/:

uv run --no-project --python .venv python manage.py `
  startapp events

macOS shell or Linux/WSL Bash, in otahque/:

uv run --no-project --python .venv python manage.py \
  startapp events

As with startproject, success returns to the prompt without a message. Open the folder in your editor. The new files are inside events/; everything else, including config/, is unchanged from Chapter 6:

otahque/
    .python-version
    .venv/
    check_environment.py
    manage.py
    config/    (unchanged)
    events/
        __init__.py
        admin.py
        apps.py
        migrations/
            __init__.py
        models.py
        tests.py
        views.py

If you see events/ somewhere else, such as inside config/, or Django reports an error, do not run the command again. “When something goes wrong”, at the end of this part, shows how to diagnose and recover without losing work.

Step 3: Read the generated files

Table 7.4 lists each generated file and its job. Most contain only an import and a comment marking where code will go later. They are starting points, not working features.

Table 7.4 — Files generated by startapp events
File Job When we use it
__init__.py Marks events/ as a Python package. It is empty. Now
apps.py Defines EventsConfig, the app’s configuration class. Step 5
models.py Will describe the records the app owns. Chapter 16
migrations/__init__.py Makes migrations/ a package for recorded database changes. No migration file exists yet. Chapter 18
admin.py Will register models with the administration site. Chapter 23
views.py Will hold the functions that answer requests. Chapter 10
tests.py Will hold the app’s automated tests. Chapter 9

Our explicit installation entry will name EventsConfig in apps.py, so that file is the one to inspect now. Open it and compare it with the Custom Way listing; it is the same class. Then add two docstrings, as Chapter 6 did for check_environment.py: one at the top for the module, and one as the first line inside the class:

"""Configuration Django reads to load the events app."""
from django.apps import AppConfig


class EventsConfig(AppConfig):
    """The events app: events and their pages."""

    name = 'events'

From Chapter 4, you can read this as a class, EventsConfig, that inherits from Django’s AppConfig and sets one class attribute. name is the full dotted path of the app’s package, here simply events. Django creates one object of this class when it loads the app.

Some files you might expect are missing. There is no urls.py and no templates/ folder. startapp creates the minimum, and we add routes in Chapter 9 and templates in Chapter 11, when the first page needs them. Do not create placeholders now.

Que. 8 events/migrations/ now exists. Have we created or applied a migration?

Flip to check your answerFold answer back

Answer. No. The folder contains only an empty __init__.py, which makes it a package ready to hold migration files later. No migration file exists, and the database is untouched. Migrations stay unapplied until the custom user is chosen in Chapter 17.

Step 4: Confirm that generated is not installed

Run the system check from Chapter 6 again, in PowerShell, a macOS shell, or Linux/WSL Bash, still beside manage.py:

uv run --no-project --python .venv python manage.py check

Expected result:

System check identified no issues (0 silenced).

The check passes, but that does not mean Django is using events. Nothing in the settings mentions it yet, so Django does not load it. The check command can also check a single app by its label. Ask it about events:

uv run --no-project --python .venv python manage.py check events

Expected result: a traceback, which Django prints when a command stops with an error. Only the first and last lines are shown here:

Traceback (most recent call last):
  [...]
LookupError: No installed app with label 'events'.

The last line is the message to read: the package exists, but it is not an installed app. This failing check is useful evidence. After Step 5, the same command should pass.

In practice: generating once

Situation. Raj is unsure whether startapp worked, because it printed nothing, and considers running it again.

Application. Look in the editor first. If events/ and its files are present, generation succeeded. Running startapp events again is refused, because events is now importable, and Django leaves the existing files untouched.

Consideration. Generation is a starting action, not a repair. If a generated file seems wrong, compare it with a freshly generated copy, as shown at the end of this part, rather than regenerating over your work.

Step 5: Install the app

Open config/settings.py and find the INSTALLED_APPS list. Add one line after django.contrib.staticfiles, keeping the comma at the end of the line. The list should now read:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'events.apps.EventsConfig',
]

Save the file and change nothing else in it. The new entry is a dotted path to the class in apps.py: events.apps is the module, and EventsConfig is the class inside it. Naming the class tells Django exactly which configuration to use. You will also see the shorter entry 'events' in guides. It works here too, because apps.py defines exactly one AppConfig class, but list the app once, in one form only. Django processes the list in order; we put our app after Django’s own so the framework’s apps are set up first.

Que. 9 What do the two halves of events.apps.EventsConfig refer to?

Flip to check your answerFold answer back

Answer. events.apps is the dotted path to the module apps.py inside the events package. EventsConfig is the class defined in that module. Together they tell Django to import events.apps and use EventsConfig as the app’s configuration.

Step 6: Confirm with the system check and the registry

Run both checks again, in PowerShell, a macOS shell, or Linux/WSL Bash, beside manage.py:

uv run --no-project --python .venv python manage.py check
uv run --no-project --python .venv python manage.py check events

Expected result, once for each command:

System check identified no issues (0 silenced).
System check identified no issues (0 silenced).

The second line is the change that matters: before installation, check events stopped with LookupError; now Django finds an installed app with the label events and checks it. A development server left running from Chapter 6 needs a restart, or at least a reload, before it uses the new list.

The registry described under the hood was built for our project as Figure 7.3 shows. All three phases still run for our app. Django imports the generated models.py, which defines no model classes yet, and calls the inherited ready() method, which does nothing because we have supplied no start-up code.

INSTALLED_APPS in config/settings.py, read in list order, feeds three stages in a row: 1, import each entry and create its AppConfig; 2, import each app’s models module; 3, run any start-up code in ready(). A note under stage 1 says a missing module, misspelled class, or repeated label stops loading there. After stage 3, an arrow leads to the app registry, which lists events with name events, label events, and verbose name Events, and is used by the check command, the admin, file lookup, and migrations.
Figure 7.3 — Django loads installed apps in three stages and records them in its registry.

Django’s shell command starts Python with the project’s settings loaded, so we can ask the registry directly. The -c option runs the quoted lines and exits. The quoted text spans three lines; type it exactly, including the final double quote. In PowerShell, a macOS shell, or Linux/WSL Bash:

uv run --no-project --python .venv python manage.py shell -c "
from django.apps import apps
config = apps.get_app_config('events')
print(config.name, config.label, config.verbose_name)"

Expected result:

12 objects imported automatically (use -v 2 for details).

events events Events

The first line comes from the shell itself: it imports some commonly used names for convenience and reports how many. The last line is our print. get_app_config looks an app up by its label and returns the configuration object Django created. Table 7.5 explains the three values.

Table 7.5 — The events app’s configuration
Attribute Value Meaning
name events The full dotted path of the app’s package, set in apps.py.
label events A short name, unique in the project. By default, the last part of name. Used in default table names and migration files.
verbose_name Events A readable name for screens such as the administration site. By default, the label with each word title-cased (label.title()).

None of this used the database. Checking and looking up apps does not create tables or apply migrations, so the unapplied-migration state from Chapter 6 is unchanged.

Que. 10 If get_app_config('events') succeeds, what has been confirmed, and what has not?

Flip to check your answerFold answer back

Answer. Django imported the entry from INSTALLED_APPS, created EventsConfig, and recorded the app under the label events. That confirms installation. It does not show that the app does anything useful: it has no models, routes, views, or templates yet.

Try it yourself

Do not change apps.py for this exercise. Suppose EventsConfig gained the line verbose_name = 'Community events'. Predict what the registry lookup would print, and say whether the label, and so the default table names, would change.

Que. 11 What would the lookup print?

Flip to check your answerFold answer back

Answer. It would print events events Community events. verbose_name only replaces the readable name. name still comes from apps.py, and label still defaults to the last part of name, so default table names would still begin with events_.

When something goes wrong

Raj follows the same steps on his computer, but his check ends with a long traceback. Regenerating the app or the project would throw away the clue. Most app problems come from one of a few places: the folder where a command ran, the name chosen, or the INSTALLED_APPS entry. A traceback lists the calls that led to an error, and its final line names the error itself; for app problems, that last line is usually enough. Table 7.6 pairs the messages we reproduced under Django 6.1.2 with their causes and a recovery.

Table 7.6 — App problems and non-destructive recovery
Observed problem Likely cause Check and recovery
can't open file … manage.py The command ran in a folder without manage.py. Return to otahque/, beside manage.py, and run it there.
CommandError: … conflicts with the name of an existing Python module The name is already importable, or the app was already generated. Nothing was created. Choose another name; for events, inspect the existing folder instead of regenerating.
CommandError: … is not a valid app name The name is not a Python identifier. Use letters, digits, and underscores, not starting with a digit.
check passes, but check events gives LookupError: No installed app with label 'events' The app is not listed in INSTALLED_APPS. Add the entry as shown in Step 5.
ModuleNotFoundError: No module named 'events' events/ is not beside manage.py, for example it was generated inside config/. Find the folder. If it holds only generated files, move it beside manage.py, as shown below.
ImportError: Module 'events.apps' does not contain a 'EventConfig' class. Choices are: 'EventsConfig'. The class name in the entry is misspelled. Correct the entry to the name Django lists.
ModuleNotFoundError: No module named 'django.contrib.staticfilesevents' A comma is missing at the end of the line before the new entry. Add the comma; each entry ends with one.
ImproperlyConfigured: Application labels aren't unique, duplicates: events The app is listed twice, for example as events and as events.apps.EventsConfig. Keep one entry.

Each correction changes one line or moves one generated folder. None of them needs a new project, a reinstall, or a database change. After any correction, rerun check and check events and expect both to report no issues.

Common Error: the missing comma

Python joins string literals that stand next to each other with nothing between them. Without the comma, 'django.contrib.staticfiles' and 'events.apps.EventsConfig' become one string, and Django tries to import a module, django.contrib.staticfilesevents, that was never written anywhere in the file. When an error names a module you never typed, look for a missing comma on the line above.

Move a misplaced app without losing work

If startapp ran from the wrong folder, events/ ends up in the wrong place. Running the command from inside config/, for example, creates config/events/, and Django cannot import it as events. First confirm that there is no events/ folder beside manage.py and that the misplaced folder holds only the generated files from Table 7.4. Then move it from otahque/. PowerShell:

Move-Item config/events events

macOS shell or Linux/WSL Bash:

mv config/events events

Both commands move the folder; they do not copy or delete its contents. If an events/ folder already exists beside manage.py, stop: compare the two folders instead of moving one over the other. Then rerun the two checks.

Compare with a fresh app when needed

If you suspect an accidental edit to a generated file, generate a fresh events app in a new, empty sibling folder and compare the file. You need this only when something has gone wrong. As in Chapter 6’s comparison-copy recovery, the commands work outside your project, so they do not touch it. If otahque-compare-app already exists, stop and choose a new unused sibling name in both commands. If you named your work folder otahque-learning, use that name in place of otahque. PowerShell, starting in otahque/:

cd ..
mkdir otahque-compare-app
cd otahque-compare-app
uv run --no-project --python ../otahque/.venv `
  python -m django startapp events
cd ../otahque

macOS shell or Linux/WSL Bash, starting in otahque/:

cd ..
mkdir otahque-compare-app
cd otahque-compare-app
uv run --no-project --python ../otahque/.venv \
  python -m django startapp events
cd ../otahque

The last command returns you to otahque/. Every generated app file is identical for the same Django version and name, so any difference is a change in your copy. Correct only the unintended change in your own file. Do not install the comparison copy or copy it over your project. Delete otahque-compare-app/ when you have finished.

In practice: reporting an app problem

Situation. Raj asks for help with his failing check.

Application. Send the command, the last line of the error, and the INSTALLED_APPS list. For the problems in Table 7.6, those three items usually identify the cause without any further detail.

Consideration. Remove anything private before sharing, such as your secret key or personal folder names. The last line names the error, but not always its cause: a ModuleNotFoundError can come from a misplaced folder or a missing comma.

Try it yourself

Diagnose two reports on paper. In the first, check passes but check events ends with LookupError: No installed app with label 'events'. In the second, check ends with ImportError: Module 'events.apps' does not contain a 'EventConfig' class. Choices are: 'EventsConfig'. For each, name the cause and the smallest correction.

Que. 12 What should the two diagnoses say?

Flip to check your answerFold answer back

Answer. In the first report, the app exists but is not installed: add events.apps.EventsConfig to INSTALLED_APPS. In the second, the entry is listed but its class name is misspelled: change EventConfig to EventsConfig, as the message suggests. Neither needs regeneration.

PAGE 003

Verify Your Work

Automated tests begin in Chapter 9, once there is a page whose result we can assert. For now, run the checks in Table 7.7 from otahque/. All of them must pass before Chapter 8.

Table 7.7 — Verification checklist for Chapter 7
Check Command or action Expected result
App folder in place Look beside manage.py in your editor events/ with the seven generated files from Table 7.4
Entry installed Open config/settings.py 'events.apps.EventsConfig' listed once, after django.contrib.staticfiles
Project configuration uv run --no-project --python .venv python manage.py check System check identified no issues (0 silenced).
App configuration uv run --no-project --python .venv python manage.py check events System check identified no issues (0 silenced).
Registry lookup The shell -c command from Step 6 events events Events, after the shell’s import line
Database untouched Recall the commands you ran No migrate command has been run

If check events still reports LookupError, the entry did not take effect: compare your list with Step 5, save the file, and run the check again. If any other command fails, find its last line in Table 7.6.

PAGE 004

Checkpoint: Quiz and Challenge

Quiz

Que. 13 What is the difference between an importable package and an installed app?

Flip to check your answerFold answer back

Answer. Any package Python can find can be imported. Only a package listed in INSTALLED_APPS is an installed app, so only then does Django register it and look inside it for models, templates, and other app files.

Que. 14 Which three questions draw an app boundary?

Flip to check your answerFold answer back

Answer. Responsibility: what the app answers for. Data ownership: which records it defines and keeps correct. Dependency direction: which apps it refers to, and which should not need to refer back to it, so that no circular dependency forms.

Que. 15 Why did we create events now but leave accounts and registrations for later?

Flip to check your answerFold answer back

Answer. The next chapters need events only. Creating the others now would add unused names and settings and freeze early guesses, while the boundary decision in Table 7.3 already records where they will go.

Que. 16 Why does check pass before the app is installed, while check events fails?

Flip to check your answerFold answer back

Answer. The plain check examines the project’s current configuration, which has no problems; it does not know that an events package exists. check events asks for an installed app with that label, and until the entry is listed there is none, so Django raises LookupError.

Que. 17 In what order does Django load installed apps?

Flip to check your answerFold answer back

Answer. In the order of INSTALLED_APPS, in three phases: it imports each entry and creates its configuration, then imports each app’s models module, then runs each configuration’s ready() method.

Mini-Challenge

Otahque will later record where events take place: a venue with a name, an address, and accessibility notes. Using the three boundary questions and Table 7.2, decide on paper whether venues belong in the events app or in a new app, and write a one-row decision record in the shape of Table 7.3. Do not create anything in your project.

Que. 18 What would a reasonable decision say?

Flip to check your answerFold answer back

Answer. Either answer can be defended if the reasons are stated. If a venue matters only as a detail of an event, events can own it. If venues are shared between many events, managed by organizers, and checked for accessibility on their own, a venues app owning venue records, with events referring to venues, gives a clearer boundary. A good record states the responsibility, the records owned, the dependency direction, and when to revisit, for example when venues gain their own pages.

What We Learned

  • A Django app is a package that supplies one capability; an installed app is one listed in INSTALLED_APPS, and the project is the configuration that assembles them.
  • The generated project already uses six apps from django.contrib, and an app can supply a capability without owning database tables.
  • Boundaries come from the product: responsibility, data ownership, and dependency direction, decided before the first model because default table names follow the app label.
  • We created only events now, recorded why in Table 7.3, and left accounts for Chapter 17 and registrations for Chapter 20.
  • startapp generates the minimum package; installing it is one line in INSTALLED_APPS, and the check command and the registry prove that Django loaded it.
  • Most app problems are diagnosed from the last line of the traceback and fixed by changing one line or moving one folder, never by regenerating.

Key terms

Use Table 7.8 to explain apps and boundaries without relying on memorized commands.

Table 7.8 — Key terms from Chapter 7
Term Meaning in this chapter
Django app A Python package that supplies related website features.
Installed app An app the project registers through INSTALLED_APPS.
INSTALLED_APPS The setting listing the project’s installed apps, processed in order.
App boundary The line between what one app is responsible for and what belongs to another.
Data ownership Which app defines a kind of record and keeps it correct.
Dependency direction Which apps depend on which other apps; avoid circular dependencies.
startapp The management command that generates a new app package.
AppConfig The class describing an app’s configuration; EventsConfig for our app.
App label An app’s short, unique name, used in default table names and migration files.
verbose_name An app’s readable name for display.
App registry Django’s record of the installed apps and their configuration, built at startup.
Traceback The list of calls leading to an error, ending with the error itself.

Readiness checkpoint: explain the difference between a package, an app, and an installed app; name the six generated apps; justify creating only events now using Table 7.2; point to each generated file and its job; show events.apps.EventsConfig in INSTALLED_APPS; run check and check events with no issues; and print the app’s name, label, and verbose name from the registry. Return to the relevant part if any result is missing.

Git Commit

There is nothing to commit yet. Git is set up for the project in Chapter 8, together with .gitignore and a recorded set of dependencies, and that chapter’s first commit will include the events app. From Chapter 8 onward, every chapter ends with a commit.

PAGE 005

Test Your Knowledge: Interview Questions

These five questions rehearse the chapter at interview level, one at each of five levels from junior to lead. L1 and L2 check what you have just learned. L3 asks how it works underneath. L4 and L5 ask about the design and leadership decisions that later chapters build on: attempt them now, and return to them when you reach those chapters. Use the readiness checkpoint to decide whether to continue. If an answer is difficult, revisit its worked example and explain the result in your own words. L4 and L5 are extension questions, not a gate to the next chapter.

L1 (Junior): What does INSTALLED_APPS do?

What the interviewer is testing: Do you know what installing an app means, as opposed to importing it?

Flip to check your answerFold answer back

Perfect answer: It lists the apps the project registers, in order. At startup Django imports each entry and builds its app registry, and installed apps can then supply models and migrations, templates, static files, management commands, and checks. A package that is not listed can still be imported as ordinary Python, but Django does not treat it as an installed app. An entry can name a package, such as 'events', or an AppConfig class, such as 'events.apps.EventsConfig'.

Table 7.9 — An importable package compared with an installed app
Question Importable package Installed app
Can Python import it? Yes Yes
Listed in INSTALLED_APPS? No Yes
In Django’s app registry? No Yes
Models, templates, and commands found automatically? No Yes
Example in our project config/ events

Behind the scenes:

# django.setup() calls apps.populate(settings.INSTALLED_APPS)
# for each entry:  AppConfig.create(entry) -> one config object
# apps.is_installed(name) then checks the registered configs
# by dotted name; nothing else in the work folder is consulted.

Code proof: in PowerShell, a macOS shell, or Linux/WSL Bash, beside manage.py:

uv run --no-project --python .venv python manage.py shell -c "
from django.apps import apps
print(apps.is_installed('events'))
print(apps.is_installed('config'))"
12 objects imported automatically (use -v 2 for details).

True
False

Common mistakes:

  • Thinking that listing an app is what makes it importable.
  • Forgetting a comma, so that two entries join into one name.
  • Listing the project package itself as an app.

Follow-up the interviewer might ask:

  • “Why does the order of INSTALLED_APPS matter?”
  • “What is the difference between 'events' and 'events.apps.EventsConfig'?”

L2 (Mid-Level): Walk through creating and installing an app, and how you confirm that Django loaded it.

What the interviewer is testing: Can you carry out the steps and verify each one, rather than assume it worked?

Flip to check your answerFold answer back
Five numbered steps from top to bottom: run startapp beside manage.py; the events package is generated; check events fails because the app is not installed; add EventsConfig to INSTALLED_APPS; check and the registry confirm the app.
Figure 7.4 — From generating an app to proving it is installed.

Perfect answer: From the folder that contains manage.py, manage.py startapp events generates the package, including apps.py with EventsConfig, models.py, and an empty migrations package. Before it is installed, check passes but check events fails with LookupError, because Django does not know the label. After adding 'events.apps.EventsConfig' to INSTALLED_APPS, both checks pass, and the registry returns the app’s name, label, and verbose name. Each step has evidence, so nobody has to assume the app is in use.

Behind the scenes:

# startapp is a TemplateCommand: it validates the name, refuses
# names that are already importable, then copies the files in
# django/conf/app_template/, rendering each *.py-tpl as *.py.

Code proof: list the template Django copies, in PowerShell, a macOS shell, or Linux/WSL Bash:

uv run --no-project --python .venv python -c "
import django, pathlib
base = pathlib.Path(django.__file__).parent
for item in sorted((base / 'conf/app_template').iterdir()):
    print(item.name)"
__init__.py-tpl
admin.py-tpl
apps.py-tpl
migrations
models.py-tpl
tests.py-tpl
views.py-tpl

Common mistakes:

  • Running startapp inside config/, so the app cannot be imported as events.
  • Choosing a name that clashes with a Python module, such as calendar.
  • Generating the app and forgetting to install it.

Follow-up the interviewer might ask:

  • “What does startapp refuse to do?”
  • “Why does check pass before the app is installed?”

L3 (Senior): What happens when Django loads the installed apps at startup?

What the interviewer is testing: Do you understand the phases of the app registry and what each phase allows?

Flip to check your answerFold answer back
Five numbered steps from top to bottom: read INSTALLED_APPS in order; import each entry and create its AppConfig; import each app’s models module; run each ready method; the registry is fully ready for use. Model classes are available once the models modules have been imported.
Figure 7.5 — The three phases that build the app registry.

Perfect answer: Django works through INSTALLED_APPS in three phases. First it imports each entry and creates its AppConfig; labels must be unique, so a repeated label stops loading with ImproperlyConfigured. Second, it imports each app’s models module, if there is one. Third, it calls each configuration’s ready() method and marks the registry ready. Model lookup becomes available after phase 2, and ready() may import model classes. Keep model imports out of apps.py at module level, and avoid database queries during initialization. The registry keeps the order of INSTALLED_APPS, which later decides, for example, whose template wins when two apps provide one with the same name.

Behind the scenes:

# Phase 1: for entry in installed_apps:
#              app_config = AppConfig.create(entry)
#          duplicate labels -> ImproperlyConfigured
# Phase 2: for app_config in configs: app_config.import_models()
# Phase 3: for app_config in configs: app_config.ready()
#          self.ready = True

Code proof: ask whether the registry has finished loading:

uv run --no-project --python .venv python manage.py shell -c "
from django.apps import apps
print(apps.ready)"
12 objects imported automatically (use -v 2 for details).

True

Common mistakes:

  • Importing models at the top of apps.py.
  • Querying the database in ready().
  • Assuming ready() can never run twice; Django’s documentation notes that it can, for example in tests.

Follow-up the interviewer might ask:

  • “Where would you connect code that must run at startup?”
  • “Why does a misspelled class name fail in the first phase?”

L4 (Staff): How do you decide app boundaries, and what goes wrong when they are drawn badly?

What the interviewer is testing: Can you draw boundaries by responsibility and data ownership, and spot the cost of bad ones?

Flip to check your answerFold answer back
Five numbered steps from top to bottom: name the app’s responsibility; list the records it owns; check which apps it refers to; keep the arrows pointing one way; record the decision and when to revisit it.
Figure 7.6 — Deciding an app boundary before the first model.

Perfect answer: Give each app one responsibility and the records that go with it: events for what is offered, accounts for who people are, and registrations for who holds a place. In the proposed record-reference diagram, registrations refers to events and accounts. Avoid circular imports when implementing operations that cross those boundaries. The arrows show which records refer to which; some operations still need information across a boundary, such as the registration count when capacity is reduced, and that should be obtained deliberately rather than by reversing the dependency. Bad boundaries show up as circular imports, changes that always touch several apps, catch-all apps such as utils, or one large app on which everything depends. Decide before the first model, because the app label becomes part of each default table name.

Behind the scenes:

# A model's default table name is built from its app label:
#     db_table = "%s_%s" % (app_label, model_name)
# so Event in the events app is stored as events_event, and
# its migrations live in events/migrations/.

Code proof: Django’s own Group model shows the pattern:

uv run --no-project --python .venv python manage.py shell -c "
from django.contrib.auth.models import Group
print(Group._meta.app_label, Group._meta.db_table)"
12 objects imported automatically (use -v 2 for details).

auth auth_group

Common mistakes:

  • One app per model or per page.
  • Naming apps after technology, such as forms, instead of responsibility.
  • Splitting before the responsibility is clear.

Follow-up the interviewer might ask:

  • “Where should the logic for cancelling a registration live?”
  • “What does it cost to move a model to another app later?”

L5 (Lead): The team wants to split Otahque into many small apps now, “to be ready for scale”. How do you respond?

What the interviewer is testing: Can you weigh the cost of structure against its benefit, and set conditions for change?

Flip to check your answerFold answer back
Five numbered steps from top to bottom: ask which problem the split solves; record the agreed boundaries; create each app when a chapter needs it; watch for the signs that justify a split; decide the user model before the first migration.
Figure 7.7 — Responding to a proposal to split early.

Perfect answer: Start with the problem, not the structure: ask which problem the split would solve. Boundaries are easiest to change before stored data exists, but splitting early adds references between apps, dependencies between migrations, and coordination, without a present benefit. Agree the proposed boundaries as a decision (Table 7.3: events now, accounts in Chapter 17, registrations in Chapter 20), create each app when a chapter needs it, and record the signs that justify a split: an app with unrelated responsibilities, changes that keep crossing one boundary, or a capability worth reusing. One boundary must be decided early: the user model is best chosen before the first migration, because Django cannot switch it automatically afterwards, which is why accounts is planned before any migration is applied. Explaining that reasoning to the team matters as much as the decision, so that the next proposal is argued from the same criteria.

Behind the scenes:

# AUTH_USER_MODEL must be chosen before the first migrate:
# auth's migrations, and every app that refers to users,
# record the user model they depend on. Changing it after
# tables exist is a difficult manual migration.

Code proof: the shipped auth migrations are still unapplied in our project. PowerShell:

uv run --no-project --python .venv python manage.py `
  showmigrations auth

macOS shell or Linux/WSL Bash:

uv run --no-project --python .venv python manage.py \
  showmigrations auth
auth
 [ ] 0001_initial
 [ ] 0002_alter_permission_name_max_length
 [ ] 0003_alter_user_email_max_length
[...]

Common mistakes:

  • Splitting by team structure or by fashion.
  • Ignoring the migration work that moving models requires later.
  • Making the change without recording why.

Follow-up the interviewer might ask:

  • “Which boundary is hardest to change later, and why?”
  • “How would you review a proposal for a new app?”

Next: Chapter 8 prepares the project for change over time: settings for different environments, a recorded set of dependencies, and Git.

PAGE 006