ContentsClose contents
Pre-release
Chapter 13 · Static files and CSS fundamentalsCHAPTER 13

Complete six-part pre-release for review. Sample events are in memory and are not published records.

Working towards: Browsable event pages (Chapter 14). A styled list of upcoming events, labelled as sample data, with a page for each event and the first automated tests. All milestones

CHAPTER THIRTEEN

Static files and CSS fundamentals

Stage 2: Pages and design (Chapters 9 to 14)

Prerequisites: Chapters 4, 8, 9, 10, 11, and 12, including the Chapter 12 project, its 14 passing tests, and your own .env

What you’ll build: one shared stylesheet that Django finds and every Otahque page loads, making the navigation, sample event list, and detail page readable and keyboard-friendly without changing what they say.

Why This Matters

Soni opens the Otahque pages from Chapter 12 to judge whether they are ready to show to members. Every page now shares a layout and navigation, but the browser draws them all with its default styles: black text running the full width of a wide screen, blue underlined links, and nothing that separates the navigation from the page or one event from the next. She can read it, but she has to work to find where the navigation stops and the content begins.

Sam could fix that by adding colours and spacing to each template. We met that kind of repetition in Chapter 12: the first page he forgets drifts away from the others. Presentation needs the same treatment we gave the layout, defined once and shared by every page.

This chapter gives Otahque its first stylesheet. It lives in one file that Django finds, every page links to it through the shared layout, and it uses a few named hooks in the HTML instead of styling inside the templates. The pages keep their words, routes, and tests. Only how they look changes.

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

  • explain how static files differ from templates and from files that users upload;
  • configure a project static folder and prove that Django finds a file in it;
  • link a stylesheet with {% load static %} and {% static %}, and test the generated link;
  • write CSS rules with element and class selectors, and describe the box model;
  • explain which rule wins when two disagree, and diagnose a rule that does not apply;
  • keep keyboard focus visible and text readable, with measured contrast.

This chapter styles the existing pages with plain CSS. Tailwind, daisyUI, and Otahque’s design system arrive in Chapter 14. Layout systems such as Flexbox and Grid, custom fonts, images, and uploaded files wait for later chapters, and preparing static files for a real server is part of deployment in Chapter 63. We add no dependency, model, or migration.

PAGE 001

What You Need to Know

Three kinds of files a page depends on

So far every response has been HTML that a view builds from a template. A styled page also needs files that are sent to the browser exactly as they are, such as a stylesheet, a script, or a logo. Django calls these static files: they belong to the code of the site and change only when we change the code.

A third kind looks similar but is very different. When a member uploads something, such as an event cover image in a later chapter, that file comes from a user at run time. Django calls it media. It needs storage, size limits, and checks that static files do not, so Django keeps the two apart from the start. Table 13.1 compares all three.

Table 13.1 — Templates, static files, and media compared
Question Templates Static files Media
Who writes it We do We do Users, at run time
What the browser receives HTML rendered with context The file, unchanged The file, after checks
Where Django looks Template folders Static folders A storage location
Otahque example templates/base.html static/otahque/site.css A future event cover (Chapter 42)

New Tool: Django’s static files app

What problem exists? The browser asks for a stylesheet by address. Something has to turn that address into the right file on disk, and every template has to write the address the same way.

What did people do before? They copied files into a folder that the web server published and typed paths such as /static/site.css into each page. When the folder or address changed, every page had to change too.

What is the static files app? django.contrib.staticfiles, already in INSTALLED_APPS since Chapter 6. It searches known folders for a file by its relative name, called finding it, and gives templates the {% static %} tag, which builds the file’s address from the STATIC_URL setting.

Why use it? The name in the template, such as otahque/site.css, stays the same wherever the file is stored and however it is served. During development, the development server sends found files for us.

Now let’s use it.

Three settings and one tag do the work. STATIC_URL, already 'static/' in our settings, is the start of every static address, so otahque/site.css is served at /static/otahque/site.css. STATICFILES_DIRS lists extra folders to search; we will add a project-level static folder, just as Chapter 12 added a project-level templates folder through DIRS. Django also searches a static folder inside each installed app, with no setting; packaged apps such as the admin bring their files that way. In a template, {% load static %} makes the tag available, and {% static 'otahque/site.css' %} writes the address.

The otahque/ folder inside static is a namespace. Two folders can each hold a file called site.css, and Django uses the first match it finds, so a bare name invites a clash. A folder named after its owner keeps the name unique, just as events/templates/events/ did for templates. Otahque keeps all its own static files in the one project folder, with a subfolder for each owner: static/otahque/ for what the whole site shares, and a folder named after an app, such as static/events/, for files only that app uses. Figure 13.1 follows the stylesheet from the file to the browser.

Four numbered steps from left to right. Step 1, the source file static/otahque/site.css in the project. Step 2, the static tag in base.html writes the address /static/otahque/site.css into the page. Step 3, the browser reads the page and requests that address. Step 4, the development server asks the finder for otahque/site.css, finds the file, and returns it with a 200 response, but only while DEBUG is True.
Figure 13.1 — A stylesheet’s route from the project folder to the browser.

Under the Hood: how a stylesheet request reaches the finder

When django.contrib.staticfiles is installed, runserver wraps the application in a small handler. For each request, the handler checks whether the path starts with STATIC_URL. If it does, the request never reaches our URL patterns, views, or middleware: the handler removes the prefix, asks each finder for the remaining name, and sends the first file found, or a 404 if none matches. It does this only while DEBUG is True. The response carries the file’s modification time, so on a later visit the browser can ask whether the file has changed, and receive a short “304 Not Modified” answer instead of the whole file. The {% static %} tag takes no part in any of this. It only joins STATIC_URL and the name, and it never checks that the file exists.

That last point matters when something goes wrong. A correct-looking link proves only that the template wrote an address. Whether the file behind it exists is a separate question. The findstatic management command answers it by printing where the finder found the file. We will use both checks.

Reading a CSS rule

New Concept: a CSS rule

What problem exists? HTML says what each part of a page is: a heading, a navigation area, a list. It says nothing about how those parts should look.

What did people do before? Early HTML put presentation inside the markup, with attributes for colour and font on each element. Every page repeated them, and changing the look meant editing every page.

What is a CSS rule? Cascading Style Sheets (CSS) describe presentation separately from the HTML. A rule has a selector, which chooses elements, and a block of declarations, each a property and a value, such as color: #0759ce;.

Why CSS? One stylesheet styles every page that links to it, so the look changes in one place and the HTML keeps meaning only what it says.

Now let’s use it.

Here is a rule from the stylesheet we will write, followed by Table 13.2, which names each part:

.event-row {
  padding: 1rem;
  border: 1px solid #d5dde8;
}
Table 13.2 — The parts of a CSS rule
Term Meaning In the example
Selector Chooses the elements the rule applies to .event-row
Class selector Matches elements whose class attribute has that name .event-row matches class="event-row"
Element selector Matches every element of one type main or a
Declaration One property set to one value, ending in a semicolon padding: 1rem;
Property What to change padding, border
Value What to change it to 1rem, 1px solid #d5dde8

Values use a few units. px is a fixed size on screen, and rem is a multiple of the root font size, so 1rem is normally 16 pixels and grows when a reader enlarges the text. Colours such as #0759ce give red, green, and blue amounts in hexadecimal.

A selector can combine parts. .site-nav a matches links inside the element with the site-nav class and no others. a:focus-visible matches a link while it has keyboard focus that the browser decides to show, which is how a keyboard user sees where they are.

Choose class names for what a thing is, not how it looks. event-row will still be right when the rows turn green; blue-box will not.

Boxes and normal flow

Every element is drawn as a rectangular box made of four layers, from the inside out: the content, the padding around it, the border, and the margin that keeps other boxes away. Padding is inside the border and shows the element’s background; margin is outside it and is always transparent. Figure 13.2 shows our event-row rule acting on one row.

On the left, the rule .event-row with its selector labelled and three declarations: padding 1rem, border 1px solid, and margin-bottom .75rem. Arrows lead from each declaration to a box on the right: the padding area around the content Sample: Python meetup, the border line around the padding, and a dashed margin area below the border, where the next row would start.
Figure 13.2 — A rule’s declarations become the layers of a box.

Without any layout rules, boxes follow normal flow. Block elements such as headings, paragraphs, lists, and main stack from top to bottom and take the full available width. Inline elements such as links and span sit within a line of text. Well-structured HTML in normal flow is already readable on every screen width, which is why we start there. Arranging boxes side by side, with Flexbox or Grid, waits until a page needs it.

When rules disagree

Two rules can set the same property on the same element. The browser settles it with the cascade, which compares candidate declarations in order and stops at the first difference. For the rules in this book, three steps matter:

  • Origin and importance. Our stylesheet beats the browser’s built-in defaults. A declaration marked !important jumps ahead, which is why it is a last resort, not a fix.
  • Specificity. A more specific selector wins. Roughly, an ID outweighs any number of classes, and a class outweighs any number of element names. .site-nav a, one class and one element, beats a, one element.
  • Order of appearance. Only when everything above is equal does the later rule win.

So “the last rule wins” is true only between rules of equal specificity from the same source. A style attribute written on an element counts as more specific than any selector, another reason to keep styles in the stylesheet. Browser developer tools show the result: the Styles panel lists every matching rule and crosses out each declaration that lost.

Try it yourself

A stylesheet contains these two rules, in this order:

.site-nav a {
  color: #ffffff;
}

a {
  color: #1b2735;
}

Que. 1 What colour is a link inside the navigation, and what colour is a link in an event row?

Flip to check your answerFold answer back

Answer. The navigation link is white. .site-nav a is more specific than a, so it wins even though a comes later. The event-row link is dark, #1b2735: .site-nav a does not match it, so a is the only rule setting its colour. Order of appearance never decided either case.

In practice: styling that keeps the page usable

Situation. Sam wants the navigation links to look cleaner, and a common snippet removes the browser’s focus outline with outline: none.

Application. That snippet leaves keyboard users unable to see which link is active. We keep the outline and restyle it with :focus-visible, in a colour that contrasts with the background behind it: white on the navy bar, blue on the pale page.

Consideration. Measure rather than guess. The Web Content Accessibility Guidelines (WCAG) 2.2 ask for a contrast ratio of at least 4.5:1 for normal text, and a free contrast checker gives the ratio for any two colours. Then press Tab through the page yourself.

The colours in this chapter come from Otahque’s recorded design direction: navy navigation, blue links, white surfaces, and dark text. Chapter 14 turns them into a design system; here they are plain values in one file.

Prefer a CSS framework now?

A framework such as Tailwind gives you a ready-made set of classes and a consistent scale. It also adds a build step and its own vocabulary, and both are easier to judge once you can read the CSS they produce. We write a small stylesheet by hand first, so that Chapter 14’s framework is a choice you understand rather than a mystery. The static files setup from this chapter carries over unchanged.

PAGE 002

How We Build It

Start from Chapter 12, in the directory containing manage.py, with your own .env, the locked environment, and 14 passing tests. We will change events/tests.py, config/settings.py, templates/base.html, templates/includes/site_nav.html, and events/templates/events/list.html. We will add one folder and one file, static/otahque/site.css. The views, URLs, and the detail and home templates do not change. At the end, every page loads the stylesheet, and the navigation, list, and detail page look like the start of a real site.

The Custom Way

This illustration shows what Django saves us from; do not add it to the project:

<link rel="stylesheet" href="/static/site.css">
<nav style="background: #142b46; padding: 12px;">
  <a href="/" style="color: white;">Home</a>
  <a href="/events/" style="color: white;">Events</a>
</nav>

The hand-typed path breaks as soon as STATIC_URL changes, for example when a later deployment serves files from another address. The style attributes repeat on every page, beat any rule in the stylesheet, and are the kind of inline style a Content Security Policy in a later security chapter can block. The Django Way keeps one name in the template and every style in one file.

The Django Way

Step 1: Write the tests first

Common Error: requesting the stylesheet in a test

It is tempting to request the stylesheet’s address in a test and expect a 200 response. Django runs tests with DEBUG set to False, whatever your settings say, so ordinary test requests are never served static files and that test fails even when everything works. Test the link in the page and the finder instead, and check the served file in the browser.

Open events/tests.py. Add one import line at the top, directly above from django.template import Context, Template:

from django.contrib.staticfiles import finders

Then add this class at the end of the file:

class StylesheetTests(SimpleTestCase):
    """Pages link the stylesheet, and Django can find it."""

    def test_pages_link_stylesheet(self):
        for url, template, title in LayoutTests.pages:
            with self.subTest(url=url):
                response = self.client.get(url)
                self.assertContains(
                    response,
                    '<link rel="stylesheet"'
                    ' href="/static/otahque/site.css">',
                    html=True,
                )

    def test_finder_locates_stylesheet(self):
        self.assertIsNotNone(
            finders.find('otahque/site.css')
        )

The first test reuses the three pages listed in LayoutTests and checks that each contains the stylesheet link, comparing it as HTML. The second asks the finder for the file by name, exactly as the development server will. finders.find returns the file’s path, or None when nothing matches.

Run the tests beside manage.py in PowerShell, a macOS shell, or Linux/WSL Bash:

uv run python manage.py test events

Expected result, shortened with ... where lines are left out:

Found 16 test(s).
System check identified no issues (0 silenced).
...........FFFF...
...
FAIL: test_finder_locates_stylesheet (events.tests...
...
AssertionError: unexpectedly None
...
FAIL: test_pages_link_stylesheet (events.tests...
...
Ran 16 tests in ...

FAILED (failures=4)

The 14 Chapter 12 tests still pass. The finder finds nothing, and each of the three pages lacks the link, so subTest reports three failures for one test. Both are the failures we expect.

Step 2: Add the project static folder

Common Error: a folder Django does not know about, or does not exist

Creating static/ without adding it to STATICFILES_DIRS leaves the finder unaware of it. Adding the setting before the folder exists makes check warn (staticfiles.W004) The directory ... in the STATICFILES_DIRS setting does not exist. Do both, and keep the folder beside manage.py, not inside an app.

In config/settings.py, find the static files section near the end and add one line below STATIC_URL, so that it reads:

STATIC_URL = 'static/'
STATICFILES_DIRS = [BASE_DIR / 'static']

Now create the folder and its namespace folder. In PowerShell, beside manage.py:

New-Item -ItemType Directory -Force static/otahque

In a macOS shell or Linux/WSL Bash, beside manage.py:

mkdir -p static/otahque

Create static/otahque/site.css with a single comment for now. CSS comments sit between /* and */:

/* Otahque shared styles */

Before writing any styles, prove that Django can find the file:

uv run python manage.py check
uv run python manage.py findstatic otahque/site.css

Expected result. The path starts with your own project folder, and macOS and Linux show forward slashes:

System check identified no issues (0 silenced).
Found 'otahque/site.css' here:
  ...\static\otahque\site.css

Run the tests again. test_finder_locates_stylesheet now passes, and the three link failures remain:

uv run python manage.py test events
Found 16 test(s).
System check identified no issues (0 silenced).
...
Ran 16 tests in ...

FAILED (failures=3)

Step 3: Link the stylesheet from the layout

Common Error: the tag without its load, or a typed path

Using {% static %} in a template that has not loaded the library fails with TemplateSyntaxError: ... Invalid block tag on line 9: 'static'. Did you forget to register or load this tag? Typing /static/otahque/site.css by hand passes today’s test but breaks when STATIC_URL changes. Use the tag, and load it in each template that uses it.

Replace templates/base.html with this version. It adds {% load static %} as the first line and a link element at the end of the head:

{% load static %}
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport"
        content="width=device-width, initial-scale=1">
  <title>{% block title %}Otahque{% endblock %}</title>
  <link rel="stylesheet"
        href="{% static 'otahque/site.css' %}">
</head>
<body>
  {% include "includes/site_nav.html" %}
  <main>
    {% block content %}{% endblock %}
  </main>
</body>
</html>

base.html extends nothing, so {% load %} can come first. The child pages do not use the tag, so they need no load of their own. Run the tests:

uv run python manage.py test events
Found 16 test(s).
System check identified no issues (0 silenced).
................
Ran 16 tests in ...

OK

All 16 pass. Now check what the tests cannot: that the browser receives the file. Start the development server:

uv run python manage.py runserver

Open http://127.0.0.1:8000/events/. The page looks the same as before, because the stylesheet holds only a comment. Open the browser’s developer tools (F12, or Cmd+Option+I in Safari after enabling its Develop menu), choose the Network panel, and tick Disable cache, so that while the developer tools are open the browser always fetches the current file instead of reusing a saved copy. Reload. The list shows site.css with status 200 and type css or stylesheet. The terminal running the server logs the same request, shown here with the date and size left out:

[...] "GET /events/ HTTP/1.1" 200 ...
[...] "GET /static/otahque/site.css HTTP/1.1" 200 ...

With the cache enabled, a later visit may show 304 instead of 200 for site.css, or no request at all: the browser is reusing its saved copy. That is useful for members and confusing while you edit, so keep the developer tools open with the cache disabled while you work on styles. Leave the server running for the next step.

Step 4: Add the hooks and the styles

Common Error: removing the focus outline, or naming classes by appearance

outline: none on links hides where keyboard focus is. Restyle the outline with :focus-visible instead. And a class such as blue-text stops being true when the design changes; name the thing, as in event-row.

The stylesheet needs a few stable names to aim at. Replace templates/includes/site_nav.html, which gains a site-nav class:

<nav class="site-nav" aria-label="Site">
  <a href="{% url 'events:home' %}">Home</a>
  <a href="{% url 'events:list' %}">Events</a>
</nav>

Replace events/templates/events/list.html. The list, each row, and the empty state gain a class; nothing else changes:

{% extends "base.html" %}
{% load event_labels %}

{% block title %}Sample events | Otahque{% endblock %}

{% block content %}
  <h1>Sample events</h1>
  <p>These fictional events are examples.</p>
  <ul class="event-list">
    {% for event in events %}
      {% partialdef event-row inline %}
        <li class="event-row">
          <a href="{% url 'events:detail' event.id %}">
            {{ event.title|sample_label }}
          </a>
        </li>
      {% endpartialdef %}
    {% empty %}
      <li class="event-empty">No sample events yet.</li>
    {% endfor %}
  </ul>
{% endblock %}

The sample-label class already exists: the Chapter 12 filter puts it on every label. Now replace static/otahque/site.css with the complete stylesheet:

/* Otahque shared styles */

body {
  margin: 0;
  font-family: system-ui, "Segoe UI", Roboto, sans-serif;
  line-height: 1.5;
  color: #1b2735;
  background: #f4f6f9;
}

main {
  max-width: 44rem;
  margin: 0 auto;
  padding: 1.5rem 1rem 3rem;
}

a {
  color: #0759ce;
}

a:focus-visible {
  outline: 3px solid #0759ce;
  outline-offset: 2px;
}

.site-nav {
  background: #142b46;
  padding: 0.75rem 1rem;
}

.site-nav a {
  color: #ffffff;
  font-weight: 600;
  margin-right: 1.25rem;
}

.site-nav a:focus-visible {
  outline-color: #ffffff;
}

.event-list {
  list-style: none;
  padding: 0;
}

.event-row,
.event-empty {
  background: #ffffff;
  border: 1px solid #d5dde8;
  border-radius: 6px;
  padding: 1rem;
  margin-bottom: 0.75rem;
}

.event-row a {
  font-weight: 600;
}

.sample-label {
  color: #9d480c;
  font-size: 0.85em;
  font-weight: 700;
}

Read it from the top. body sets the text colour, font, line spacing, and a pale page background, and removes the browser’s default margin so the navigation reaches the edges. main limits the reading width to 44rem and centres it with margin: 0 auto; its side padding keeps text off the edges of a phone screen. Links are blue, and every link’s keyboard focus gets a solid outline. The navigation is a navy bar whose links are white, with a white focus outline that shows against the navy. The event list drops its bullets and indentation, and each row, or the empty state, becomes a white box with a border, rounded corners, padding inside, and a margin below. The sample label is a smaller, bold, dark orange word. A comma between selectors, as in .event-row, .event-empty, applies one rule to both.

Save the file and reload http://127.0.0.1:8000/events/, with the developer tools still open. The navigation is now a navy bar with white links, the content sits in a centred column, and the sample event is a white card. Open the event: its heading shows the orange Sample: label. Every colour pair here has a contrast ratio of at least 5.7:1, measured with a contrast checker, above the 4.5:1 that WCAG asks for.

Run the tests again; the classes change no text the tests depend on:

uv run python manage.py test events
Found 16 test(s).
System check identified no issues (0 silenced).
................
Ran 16 tests in ...

OK

Step 5: Diagnose a competing rule, then check with the keyboard

Common Error: reaching for !important

When a rule seems ignored, adding !important usually makes it win, and hides why it lost. The next rule that needs to win then needs !important too. Find the winning rule first, then fix the selector or remove the duplicate.

To watch the cascade decide, add this experiment at the end of static/otahque/site.css, below every other rule:

/* Experiment: remove after Step 5 */
a {
  color: #1b2735;
}

Save and reload the list page. The event link turns dark, but the navigation links stay white. Right-click a navigation link, choose Inspect, and read the Styles panel. Three rules set its color. .site-nav a is listed first with #ffffff; below it, both a rules are crossed out, the new one with #1b2735 and the original with #0759ce. The newest rule lost because .site-nav a is more specific. On the event link, the new a rule crosses out the earlier a rule: equal specificity, so the later one wins.

If the change does not appear at all, the browser is probably showing its saved copy: check that Disable cache is still ticked and the developer tools are open, reload, and confirm that the request for site.css returned 200.

Now delete the experiment, the comment and the three lines below it, so that the file ends with the .sample-label rule again. Save and reload; the event link is blue once more.

Finally, check the page with the keyboard. Click the address bar, then press Tab. Focus moves to Home, with a white outline on the navy bar, then to Events, then to the sample event, with a blue outline. Narrow the browser window, or use the developer tools’ device view at a phone width: the text fits without sideways scrolling. Stop the server with Ctrl+C, then run the full suite once more:

uv run python manage.py check
uv run python manage.py test events
System check identified no issues (0 silenced).
Found 16 test(s).
System check identified no issues (0 silenced).
................
Ran 16 tests in ...

OK

As before, do not apply migrations yet.

When something goes wrong

Table 13.3 lists the problems this chapter can produce. Most come from one of three places: the file, its address, or the cascade. Check them in that order.

Table 13.3 — Static file and CSS problems and safe recovery
Symptom Possible cause What to check
TemplateSyntaxError: ... Invalid block tag on line 9: 'static'. The template uses the tag without loading it Add {% load static %} at the top of base.html
staticfiles.W004 warning from check STATICFILES_DIRS names a folder that does not exist Create static/ beside manage.py, or correct the setting
findstatic prints No matching file found The file name or folder differs, or STATICFILES_DIRS is missing Run findstatic with --verbosity 2 to list the folders searched, then compare the name
The page is unstyled and site.css shows 404 in the Network panel The finder cannot find the file, or DEBUG is not True Run findstatic; confirm .env has DJANGO_DEBUG=True, then restart the server
runserver stops with You must set settings.ALLOWED_HOSTS if DEBUG is False. .env is missing, or DJANGO_DEBUG is not True Compare .env with .env.example and restart; do not use runserver --insecure
A saved change does not appear The browser shows a cached copy, or you edited a different file Disable the cache in the Network panel and reload; compare the path with findstatic
A declaration is crossed out A more specific rule, or a later equal one, wins Read the Styles panel; fix the selector or remove the duplicate, without !important
Keyboard focus is invisible A rule removed the outline Remove outline: none and restyle :focus-visible

Two of these need care. findstatic exits successfully even when it finds nothing, so read its message rather than trusting that the command ran. And runserver --insecure forces static serving with DEBUG off; it exists for unusual local cases, and is never the fix for a missing .env value.

Keep your work while you diagnose a problem. Compare the one file a message names with its listing, and save a copy before replacing anything you want to keep. Fix one problem at a time and rerun the tests. Do not delete the project or reset Git as a first response.

PAGE 003

Verify Your Work

Run the checks in Table 13.4 beside manage.py, with the development server running for the browser rows.

Table 13.4 — Verification checklist for Chapter 13
Check Command or action Expected result
Configuration uv run python manage.py check System check identified no issues (0 silenced).
Automated checks uv run python manage.py test events Found 16 test(s). and OK at the end
Stylesheet tests uv run python manage.py test events -k Stylesheet Found 2 test(s). and OK at the end
File found uv run python manage.py findstatic otahque/site.css Found 'otahque/site.css' here: and your project's static folder
File served Network panel on http://127.0.0.1:8000/events/ site.css with status 200, or 304 on a later reload
Pages styled Open home, the event list, and the Python meetup detail Navy navigation, centred column, white event card, orange Sample: label
Keyboard Press Tab from the address bar A visible outline on Home, Events, then the event link
Narrow screen Device view at a phone width No sideways scrolling
Missing event Open http://127.0.0.1:8000/events/999/ A 404 page

The 404 page is Django’s own debug page, not our layout, so it stays unstyled; custom error pages come later. The tests prove that every page links the stylesheet and that Django finds the file. The browser rows prove that the file arrives and changes how the pages look. Neither proves the other. The official references for this chapter are https://docs.djangoproject.com/en/6.1/howto/static-files/ and https://docs.djangoproject.com/en/6.1/ref/contrib/staticfiles/.

PAGE 004

Checkpoint: Quiz and Challenge

Quiz

Que. 2 How does a static file differ from a media file?

Flip to check your answerFold answer back

Answer. We write static files as part of the site’s code, and they change only when the code does. Media files are uploaded by users at run time and need storage, limits, and checks of their own.

Que. 3 What does {% static 'otahque/site.css' %} produce, and what does it not check?

Flip to check your answerFold answer back

Answer. The address /static/otahque/site.css, built from STATIC_URL and the name. It does not check that the file exists; findstatic does that.

Que. 4 Why is the stylesheet inside an otahque/ folder?

Flip to check your answerFold answer back

Answer. Django serves the first file it finds for a name. A folder named after its owner keeps otahque/site.css from clashing with another app’s site.css.

Que. 5 .site-nav a sets links white, and a later rule a sets them dark. What colour are the navigation links, and why?

Flip to check your answerFold answer back

Answer. White. .site-nav a has a class and an element, so it is more specific than a. Order of appearance only decides between rules of equal specificity.

Que. 6 Why can’t a test simply request /static/otahque/site.css and expect 200?

Flip to check your answerFold answer back

Answer. Tests run with DEBUG set to False, and the development static serving only works when DEBUG is True. We test the link and the finder, and check the served file in the browser.

Mini-Challenge

Work in a separate copy of your project, so your checkpoint stays as it is.

Que. 7 In the copy, give the home page’s introduction a lead class and a rule that makes it slightly larger and muted. Write the test first: it should check that the home page contains the paragraph with that class.

Flip to check your answerFold answer back

Answer. Add this test class at the end of events/tests.py in the copy:

class LeadParagraphTests(SimpleTestCase):
    """The home page opens with a lead paragraph."""

    def test_home_has_lead(self):
        response = self.client.get('/')
        self.assertContains(
            response,
            '<p class="lead">Find a community event'
            ' and see what it is about.</p>',
            html=True,
        )

It fails until the class exists. Then replace events/templates/events/home.html in the copy:

{% extends "base.html" %}

{% block content %}
  <h1>Welcome to Otahque.</h1>
  <p class="lead">
    Find a community event and see what it is about.
  </p>
{% endblock %}

Add the rule at the end of the copy’s static/otahque/site.css:

.lead {
  font-size: 1.15rem;
  color: #526277;
}

All 17 tests in the copy pass, and #526277 on the page background measures 5.75:1. The name says what the paragraph is, an introduction, not how it looks. Leave your main project at 16 tests for Chapter 14.

What We Learned

  • Static files are part of the site’s code and are sent unchanged; media comes from users and is handled separately.
  • STATICFILES_DIRS adds a project static folder, and a namespace folder keeps names unique.
  • {% static %} writes an address from STATIC_URL; findstatic proves the file exists.
  • The development server serves found files only while DEBUG is True, and tests run with it off.
  • A CSS rule is a selector and declarations; every element is a box of content, padding, border, and margin.
  • The cascade weighs origin and importance, then specificity, then order; developer tools show which rule won.
  • Visible focus and measured contrast are part of styling, not extras.

Key terms

Use Table 13.5 to explain this chapter’s ideas in your own words.

Table 13.5 — Key terms from Chapter 13
Term Meaning in this chapter
Static file A file of the site's code, such as a stylesheet, sent to the browser unchanged.
Media A file a user uploads at run time.
Finder The part of Django that searches static folders for a name.
Namespace folder A folder named after its owner, keeping file names unique.
Selector The part of a CSS rule that chooses elements.
Declaration A property set to a value inside a rule.
Box model Content, padding, border, and margin around every element.
Cascade How the browser chooses between conflicting declarations.
Specificity The weight of a selector, from IDs, classes, and element names.

Readiness checkpoint: you are ready for Chapter 14 when every page shows the navy navigation and centred content, the Network panel shows site.css loading, Tab shows a visible outline on each link, and all 16 tests pass. Explain why the link test alone does not prove the page is styled. Return to the relevant part if any result is missing.

Git Commit

Check the changes, then stage the new and changed files, in PowerShell, a macOS shell, or Linux/WSL Bash, beside manage.py. Read the staged changes, and press q to leave the listing:

git status --short
git add config/settings.py static templates
git add events/tests.py events/templates
git diff --cached

The folder names add every file inside them. Keep .env out of Git, as before. Then record the commit:

git commit -m "Add a shared stylesheet through static files"
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 you to diagnose a problem in order. L4 and L5 look ahead to a larger application and to deployment: attempt them now, and return to them later. They are extension questions, not a gate to the next chapter. Run each code proof beside manage.py, in PowerShell, a macOS shell, or Linux/WSL Bash.

L1 (Junior): What is a static file, and why use the static tag?

What the interviewer is testing: Can you tell static files from templates and media, and explain why addresses are generated?

Flip to check your answerFold answer back

Perfect answer: A static file is part of the site’s code that the browser receives unchanged, such as a stylesheet, a script, or an icon. Templates are different because Django renders them with context, and media is different because users upload it. The {% static %} tag builds the file’s address from STATIC_URL, so templates name the file, not the address. If the address changes later, for example when files move to another server, no template changes.

Table 13.6 — A typed path compared with the static tag
Question Typed /static/... path {% static %} tag
Where the address comes from Written in each template Built from STATIC_URL
If STATIC_URL changes Every template must change No template changes
Later file names with version hashes Not supported Supported by the storage setting
Checks the file exists No No; use findstatic

Behind the scenes:

# {% static name %} asks the static files storage for
#     the name's URL: STATIC_URL joined with the name.
#     It does not look for the file.

Code proof: build two addresses, one for a file that does not exist:

uv run python manage.py shell -c "
from django.templatetags.static import static
print(static('otahque/site.css'))
print(static('otahque/logo.svg'))
"
12 objects imported automatically (use -v 2 for details).

/static/otahque/site.css
/static/otahque/logo.svg

There is no logo.svg, yet the address is built all the same.

Common mistakes:

  • Typing /static/... into templates.
  • Treating uploaded files as static files.
  • Expecting the tag to report a missing file.

Follow-up the interviewer might ask:

  • “Where would a file a user uploads be stored instead?”
  • “What would you change to serve static files from another domain?”

L2 (Mid-Level): Trace otahque/site.css from the file to the browser.

What the interviewer is testing: Can you name each step and the check that proves it?

Flip to check your answerFold answer back
The file sits in the project static folder, findstatic proves the finder sees it, the static tag writes its address into base.html, the browser requests that address, and runserver returns it while DEBUG is True, which the Network panel confirms.
Figure 13.3 — Trace a stylesheet and prove each step.

Perfect answer: The file is static/otahque/site.css, in a folder listed in STATICFILES_DIRS; findstatic proves the finder sees it. The layout’s {% static %} tag writes /static/otahque/site.css into the page, which a test checks. The browser reads the link and requests that address. Because the path starts with STATIC_URL, the development server’s static handler takes the request before any view, asks the finders for otahque/site.css, and returns the file, while DEBUG is True. The Network panel shows the 200. Each step has its own proof, and none of them proves the next.

Behind the scenes:

# StaticFilesHandler: if the path starts with STATIC_URL,
#     strip the prefix, find the file with the finders,
#     and serve it; otherwise pass the request on.

Code proof: the file the finder uses and the address the tag writes:

uv run python manage.py shell -c "
from pathlib import Path
from django.conf import settings
from django.contrib.staticfiles import finders
from django.templatetags.static import static
found = Path(finders.find('otahque/site.css'))
print(found.relative_to(settings.BASE_DIR).as_posix())
print(static('otahque/site.css'))
"
12 objects imported automatically (use -v 2 for details).

static/otahque/site.css
/static/otahque/site.css

Common mistakes:

  • Treating a passing link test as proof that the file is served.
  • Forgetting that the request skips URL patterns and views.
  • Assuming runserver serves files with DEBUG off.

Follow-up the interviewer might ask:

  • “What does a 304 for site.css mean?”
  • “Which step changes when the site is deployed?”

L3 (Senior): A CSS rule does not apply. How do you find out why?

What the interviewer is testing: Can you diagnose in order, from the file to the selector to the cascade, without guessing?

Flip to check your answerFold answer back
First check that the page links the stylesheet and the request returns 200 rather than 404. Then check that the file contains the edited rule and is not a cached copy. Then check that the selector matches the element. Finally, read the crossed-out declaration in the Styles panel to see which rule won, and fix the cause.
Figure 13.4 — Diagnose a rule from the file to the cascade.

Perfect answer: I check the layers in order, because each one hides the next. First the file: does the page link it, and does the Network panel show 200, not 404? If it is 404, findstatic --verbosity 2 shows where Django looked. Second, freshness: is the browser using a cached copy, or did I edit a different file? Third, the selector: does it match this element, for example is the class spelled the same in the template? Last, the cascade: the Styles panel shows the declaration crossed out and the rule that beat it, by specificity or order. Only then do I change anything, and I fix the cause instead of adding !important.

Behind the scenes:

For one property on one element:
  1. collect every declaration whose selector matches
  2. compare origin and importance
  3. then specificity
  4. then order of appearance
The first difference decides; the others are crossed out.

Code proof: the first layer, a misspelled file name:

uv run python manage.py findstatic otahque/stie.css
No matching file found for 'otahque/stie.css'.

The command still exits successfully, so a script that checks only its exit code would miss the problem. Read the message, or test with finders.find as our test does.

Common mistakes:

  • Editing selectors before checking that the file loads.
  • Adding !important instead of finding the winning rule.
  • Forgetting the browser cache after an edit.

Follow-up the interviewer might ask:

  • “How would you compare the specificity of two selectors?”
  • “How could a style attribute in a template cause this?”

L4 (Staff): Where should shared and app-owned static files live?

What the interviewer is testing: Can you design static file ownership for a growing project?

Flip to check your answerFold answer back
One project static folder, found through STATICFILES_DIRS, holds every Otahque static file. Shared site files go in its otahque subfolder, and files for one app go in a subfolder named after that app, such as events. Packaged apps such as the admin bring their own static folders. When two files share a name, the first match wins, so check with findstatic.
Figure 13.5 — Place static files by ownership.

Perfect answer: I would keep the project’s own static files in one project folder found through STATICFILES_DIRS, with a subfolder for each owner. Shared presentation, such as the site stylesheet the base layout links, goes in static/otahque/. A file that belongs to one app, such as a script only the event pages use, goes in a folder named after that app, such as static/events/. One place makes the project’s assets easy to find and review, and the app-named folders still show who owns each file. Django can also find a static folder inside each app; that suits apps packaged for reuse elsewhere, such as the admin, which carry their files with them. The finders search the configured folders first, then each app in INSTALLED_APPS order, and the first match wins, so a duplicate name silently hides the other file. Namespaces prevent that, and findstatic shows which file a name resolves to.

Behind the scenes:

# find(path): ask each finder in STATICFILES_FINDERS
#     in turn; FileSystemFinder searches STATICFILES_DIRS,
#     AppDirectoriesFinder searches each app's static/.

Code proof: the finders in use and the folders they searched:

uv run python manage.py shell -c "
from pathlib import Path
from django.conf import settings
from django.contrib.staticfiles import finders
for name in settings.STATICFILES_FINDERS:
    print(name.rsplit('.', 1)[1])
finders.find('otahque/site.css', find_all=True)
for place in finders.searched_locations:
    path = Path(place).relative_to(settings.BASE_DIR)
    print(path.as_posix())
"
12 objects imported automatically (use -v 2 for details).

FileSystemFinder
AppDirectoriesFinder
static
.venv/Lib/site-packages/django/contrib/admin/static

The last line differs on macOS and Linux, where it starts .venv/lib/python3.14/. The admin app brings its own static folder. The events app has no static folder of its own, and keeps none: its files will go in static/events/.

Common mistakes:

  • Putting app-specific files in the shared otahque/ folder, so nobody can tell which app owns them.
  • Putting files straight into static/, with no owner folder.
  • Overriding a file by accident because two names match.

Follow-up the interviewer might ask:

  • “How would you deliberately override a third-party app’s stylesheet?”
  • “Where would Chapter 14’s compiled CSS live?”

L5 (Lead): How would you prepare static files for production?

What the interviewer is testing: Can you separate local serving from a deployment design, without treating runserver as a static server?

Flip to check your answerFold answer back
Keep the same static tag and names, set STATIC_ROOT, run collectstatic to copy every found file into it, use storage that adds content hashes to names, serve that folder from the web server or a static file service with long cache times, and verify the deployed pages.
Figure 13.6 — Move from development serving to a deployment plan.

Perfect answer: Development serving is a convenience: it searches folders on every request and only runs with DEBUG on, which production never has. For deployment I would keep the templates and names exactly as they are, set STATIC_ROOT to a folder outside the source, and run collectstatic during the release to copy every found file there. I would choose a storage backend that adds a content hash to each file name, so browsers can cache files for a long time and still receive changes immediately. A web server, a static file service, or a package such as WhiteNoise then serves that folder. Then I would check the deployed pages and their static responses. Otahque does this in Chapter 63, where it can be run and verified.

Behind the scenes:

# collectstatic: for every file the finders find, copy it
#     into STATIC_ROOT through the configured storage,
#     which may also rename it with a content hash.

Code proof: our project is not ready for collection, and Django says so:

uv run python manage.py collectstatic --noinput
...
django.core.exceptions.ImproperlyConfigured: You're using
the staticfiles app without having set the STATIC_ROOT
setting to a filesystem path.

The message is one line, wrapped here to fit the page. Nothing is copied, and the project is unchanged. That is the correct state for Chapter 13: no production setting without a production server to verify it.

Common mistakes:

  • Running runserver, or --insecure, as a production static server.
  • Hand-renaming files to defeat browser caches.
  • Adding production settings that nothing yet runs or checks.

Follow-up the interviewer might ask:

  • “Why do hashed file names allow long cache times?”
  • “What fails if a template names a file that collectstatic did not find?”

Next: Chapter 14 introduces Tailwind, daisyUI, and Otahque’s design system.

PAGE 006