ContentsClose contents
Pre-release
Chapter 12 · Template inheritance, includes, and partialsCHAPTER 12

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 TWELVE

Template inheritance, includes, and partials

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

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

What you’ll build: every Otahque page sharing one layout and navigation, a reusable event row, and a tested filter that labels sample titles without giving up escaping.

Why This Matters

Soni opens the fictional sample event from Chapter 11 and reads its detail page. She follows the link back to the list, but from there she has no way to reach the home page except by typing its address. The home page itself is still one line of plain text. Nothing on the three pages says they belong to the same site.

Look at the two templates we wrote in Chapter 11 and the problem is clear. Each repeats the same document head, and neither has navigation. If Sam wants a link on every page, we must edit every template, and the next page we add will need the same edit again. One forgotten file and the site disagrees with itself.

This chapter gives the pages one shared layout. Each page fills in only what is its own, the navigation lives in one file, the list row becomes a named piece we can render and test alone, and a small filter of our own labels every sample title. The events stay fictional and in memory.

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

  • explain template inheritance, blocks, and how a child page is rendered;
  • place a shared layout in a project templates folder and find it through DIRS;
  • include one template inside another and control what context it sees;
  • define a partial and render it on its own;
  • write a custom filter that adds HTML and still escapes its input, with tests.

We still use plain HTML. Styles and static files arrive in Chapters 13 and 14, stored events from Chapter 15, and forms in Chapter 24. This chapter adds no dependency, model, or migration.

PAGE 001

What You Need to Know

One layout, many pages

New Concept: template inheritance

What problem exists? Every page repeats the same outer structure: the document head, the navigation, and the main area. A change to any of them means editing every page.

What did people do before? They copied the shared parts into each file, or joined a header string and a footer string around each page in code. Both drift apart as soon as one copy is changed and another is not.

What is template inheritance? A base template holds the structure every page shares and marks named places, called blocks, that a page may fill. A child template names its parent with {% extends %} and supplies its own content for those blocks. Django renders the parent with the child’s blocks put in place.

Why inheritance? The shared structure exists once. Each page holds only what makes it different, and a site-wide change is one edit.

Now let’s use it.

A block is written {% block name %}...{% endblock %}. In the base template, whatever sits between the two tags is the fallback: it is shown when a child does not fill that block. Our layout will have two blocks. The title block holds the text in the browser tab, with Otahque as its fallback. The content block holds the page’s own content, with no fallback.

On the left, events/list.html starts with extends and fills a title block and a content block. Arrows lead to the same blocks in templates/base.html, in the middle, where the title block’s fallback is Otahque and the content block has none, below the shared structure. An arrow leads to the rendered page on the right, with the tab Sample events
Figure 12.1 — A child template fills the blocks its base template defines.

Inside a child’s block, {{ block.super }} inserts the parent’s content for that block, so a child can add to the fallback instead of replacing it. A block name may appear only once in a template.

Under the Hood: how a child is rendered

Django meets {% extends "base.html" %} and loads the parent first. It collects the child’s blocks by name, then renders the parent from top to bottom. At each block in the parent, it uses the child’s version if there is one, and the parent’s fallback if not. Anything in the child outside a block has nowhere to go and is dropped. A block name the parent does not define is dropped too, silently. That is why extends must be the first tag in the child: the whole child is read as a set of replacements for its parent.

Two of those silent cases deserve a warning now. A misspelled block name, such as contnet, raises no error; its content simply never appears. Text written in the child outside every block disappears in the same way. In both cases the page still returns 200. Our tests will check for content, not only for a successful status.

Try it yourself

Assume base.html defines a title block with the fallback Otahque and an empty content block. A child extends it and contains three things: the word Hello outside any block, a block named contnet holding Welcome, and a title block holding {{ block.super }} | Events.

Que. 1 What do the browser tab and the main area show?

Flip to check your answerFold answer back

Answer. The tab shows Otahque | Events, because block.super inserts the parent’s fallback before the child’s text. The main area is empty. Hello is outside every block, so it is dropped. contnet is not a block the parent defines, so Welcome is dropped too. Neither mistake raises an error.

Where the shared layout lives

In Chapter 11, APP_DIRS let Django find events/list.html inside the events app. A layout that every page uses belongs to no single app: accounts and registrations will need it as well, when their pages arrive in Chapters 27 and 31. So we put it in a templates folder at the project level, beside manage.py, and tell Django about it with the DIRS setting. Django searches the folders in DIRS first, then each installed app’s templates folder. Our layout will be templates/base.html, and its name in {% extends %} is simply base.html.

Que. 2 Why not put base.html in events/templates/ and leave the settings alone?

Flip to check your answerFold answer back

Answer. It would work today, but the layout would then belong to the events app. When the accounts app needs the same layout, it would depend on the events app for something that is not about events. A project-level folder makes the shared layout visibly shared.

Including one template in another

{% include "includes/site_nav.html" %} renders another template at that point and inserts its output. The included template sees the same context as the template that includes it, so it can use any variable the page has. Two options limit that. with passes extra values, as in {% include "row.html" with event=item %}, and only gives the included template nothing except what with supplies. Use only when a fragment should not depend on whatever the surrounding page happens to contain.

Our navigation will be an included template, so the layout stays short and the navigation has a file of its own. Both links will use route names with {% url %}, as Chapter 11’s links did, so a changed address needs no template edit.

Partials: a named piece of a template

New Concept: template partials

What problem exists? Some markup, such as one row of the event list, is used in one template but is worth naming: we want to test it alone, and later chapters will want to send just that row to the browser.

What did people do before? They moved the row into its own small file and included it, which scatters one page across several files. Before Django 6.0, a third-party package provided partials.

What is a partial? A named fragment defined inside a template with {% partialdef name %}...{% endpartialdef %}. It can be used in the same template with {% partial name %}, and loaded from outside as template_name#partial_name.

Why partials? The fragment stays where it is used, keeps one name, and can still be rendered on its own.

Now let’s use it.

A plain partialdef only defines the fragment; nothing appears until {% partial %} uses it. Adding inline, as in {% partialdef event-row inline %}, defines it and renders it in the same place. Our list will define the row inline, inside its loop, so the page looks exactly as before. A test can then ask for events/list.html#event-row and receive just one row, without the layout.

Table 12.1 compares the three ways to reuse template markup. Figure 12.2 shows how they will meet in our list page.

Table 12.1 — Choosing a way to reuse template markup
Mechanism Use it for Our example
Inheritance (extends) The outer structure that many pages share base.html and its two blocks
Include A self-contained piece that several templates use The site navigation
Partial A named piece used within one template, which is also worth rendering alone One event row in the list
The rendered events list page is built from three sources. base.html supplies the outer structure, the included site_nav.html supplies the navigation, and the list’s own content block repeats the event-row partial once for each sample event.
Figure 12.2 — One page assembled from a layout, an include, and a partial.

Custom filters

New Tool: a custom template filter

What problem exists? We want every sample title shown with the same visible label, Sample:, wrapped in an element that later styles can target. Writing that markup by hand in every template repeats it and invites mistakes.

What did people do before? They built the HTML string in each view, which mixes markup into Python, or repeated it in each template.

What is a custom filter? A Python function registered with Django’s template library and used after a value with |, as {{ title|sample_label }}. It lives in a templatetags package inside an installed app and is loaded into a template with {% load %}.

Why a filter? The label is defined once, can be tested alone, and is used with the same syntax as Django’s own filters.

Now let’s use it.

A filter that returns HTML must take care with its input. If it joins the title into a string and marks the result safe, it switches off the escaping we tested in Chapter 11. Django’s format_html builds the HTML from a template string with {} placeholders and escapes each argument before inserting it, then marks the result safe. Our label’s span element stays markup; the title stays text.

Two details catch everyone at least once. {% load %} is not inherited: a child that uses the filter must load it itself, even if its parent has. And the development server only discovers a new templatetags module when it starts, so restart it after creating one.

In practice: a site-wide notice

Situation. Sam wants every page to say that the events shown are fictional samples until real publishing is built.

Application. One line in base.html, inside the layout and outside every block, puts the notice on every page that extends it, with no change to the pages themselves.

Consideration. A notice in the layout appears everywhere, including pages added later. If some pages must not show it, give the layout a block for it, so those pages can replace it with nothing.

Everything in this chapter uses Django’s own template language. One alternative deserves a short answer before we build.

Prefer Jinja2?

Django can also render templates with Jinja2, a separate template engine with similar syntax. It needs installing, looks in each app’s jinja2 folder instead of templates, and does not know Django’s own tags and filters unless they are added to its environment. We keep Django’s template language: it needs no new dependency, and every later chapter and Django’s admin use it. The choices in this chapter, layout, include, partial, and filter, carry over to Jinja2 in spirit.

PAGE 002

How We Build It

Start from Chapter 11, in the directory containing manage.py, with your own .env, the locked environment, and nine passing tests. We will change events/tests.py, events/views.py, config/settings.py, and the two Chapter 11 templates. We will add templates/base.html, templates/includes/site_nav.html, events/templates/events/home.html, and a templatetags package with one module. events/urls.py does not change.

The Custom Way

This illustration shows the problem; do not add it to the project:

HEADER = '<nav><a href="/">Home</a></nav><main>'
FOOTER = '</main>'


def page(body):
    return HEADER + body + FOOTER

Every view would wrap its HTML in the same two strings. It works until one view forgets, a link changes and the header has to know it, or a body contains a title that is never escaped. The Django Way keeps the structure in a template and leaves escaping on.

The Django Way

Step 1: Write the tests first

Open events/tests.py and make three changes. First, replace the import lines at the top with these:

from unittest.mock import patch

from django.template import Context, Template
from django.template.loader import render_to_string
from django.test import SimpleTestCase
from django.urls import resolve, reverse

from . import views

Second, in EventDetailTests, replace the first assertion of test_sample_event, the one that looks for Sample: Python meetup, with this one. The detail heading will soon hold the filter’s label element, so the test compares HTML structure (html=True) rather than raw text:

        self.assertContains(
            response,
            '<h1><span class="sample-label">Sample:</span>'
            ' Python meetup</h1>',
            html=True,
        )

Third, add these three classes at the end of the file:

class LayoutTests(SimpleTestCase):
    """Every page shares the base layout and navigation."""

    pages = [
        ('/', 'events/home.html', 'Otahque'),
        ('/events/', 'events/list.html',
         'Sample events | Otahque'),
        ('/events/1/', 'events/detail.html',
         'Sample event | Otahque'),
    ]

    def test_pages_extend_layout(self):
        for url, template, title in self.pages:
            with self.subTest(url=url):
                response = self.client.get(url)
                self.assertTemplateUsed(response, template)
                self.assertTemplateUsed(
                    response, 'base.html'
                )
                self.assertContains(
                    response, f'<title>{title}</title>',
                    html=True,
                )

    def test_pages_include_navigation(self):
        for url, template, title in self.pages:
            with self.subTest(url=url):
                response = self.client.get(url)
                self.assertTemplateUsed(
                    response, 'includes/site_nav.html'
                )
                self.assertContains(
                    response,
                    '<a href="/">Home</a>',
                    html=True,
                )
                self.assertContains(
                    response,
                    '<a href="/events/">Events</a>',
                    html=True,
                )


class EventRowPartialTests(SimpleTestCase):
    """The event row partial renders one event."""

    def test_row_renders_alone(self):
        event = {'id': 1, 'title': '<b>Not a tag</b>'}
        html = render_to_string(
            'events/list.html#event-row', {'event': event}
        )
        self.assertIn('href="/events/1/"', html)
        self.assertIn('&lt;b&gt;Not a tag', html)
        self.assertNotIn('<nav', html)


class SampleLabelFilterTests(SimpleTestCase):
    """The sample_label filter marks and escapes a title."""

    def render_label(self, title):
        """Render the filter on title, as a template would."""
        template = Template(
            '{% load event_labels %}{{ title|sample_label }}'
        )
        return template.render(Context({'title': title}))

    def test_labels_title(self):
        self.assertEqual(
            self.render_label('Python meetup'),
            '<span class="sample-label">Sample:</span>'
            ' Python meetup',
        )

    def test_escapes_title(self):
        title = '<strong>Not a tag</strong>'
        html = self.render_label(title)
        self.assertIn('&lt;strong&gt;', html)
        self.assertNotIn('<strong>', html)

LayoutTests checks all three pages with one loop. self.subTest(url=url) reports each page separately, so one failing page does not hide the others. The partial test renders one row alone and checks that it links to the event, escapes its title, and carries no navigation. The filter tests render a tiny template that loads our filter, the same way a page will use it.

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 14 test(s).
System check identified no issues (0 silenced).
..FEFFFFFF...EE...
...
ERROR: test_row_renders_alone (events.tests...
...
...TemplateDoesNotExist: events/list.html#event-row
...
...TemplateSyntaxError: 'event_labels' is not a registered...
...
FAIL: test_sample_event (events.tests.EventDetailTests...
...
FAIL: test_pages_extend_layout (events.tests.LayoutTests...
...
FAIL: test_pages_include_navigation (events.tests...
...
Ran 14 tests in ...

FAILED (failures=7, errors=3)

Eight of the nine Chapter 11 tests still pass. The ninth, test_sample_event, fails because the detail heading has no label element yet. All five new tests fail or stop with an error, each for a reason we expected: no page uses base.html, nothing includes the navigation, events/list.html has no event-row partial, and there is no event_labels library to load. The count says failures=7 because subTest reports each failing page separately. Read the messages, then continue.

Step 2: Add the project templates folder and the layout

Common Error: changing APP_DIRS instead of DIRS

APP_DIRS is True or False: it switches the search of app folders on or off. The project folder is added to the list in DIRS. Setting APP_DIRS to a path does not add a folder, and setting it to False would hide the Chapter 11 templates.

In config/settings.py, find the TEMPLATES setting and change only the DIRS line, so that it reads:

        'DIRS': [BASE_DIR / 'templates'],

BASE_DIR is the folder containing manage.py, as Chapter 6 explained. Now create the folder for the layout. In PowerShell, beside manage.py:

New-Item -ItemType Directory -Force templates

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

mkdir -p templates

Create templates/base.html with this complete file:

<!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>
</head>
<body>
  <main>
    {% block content %}{% endblock %}
  </main>
</body>
</html>

This is Chapter 11’s document structure, moved to one place, with two blocks where pages differ. Check the settings, then run the tests:

uv run python manage.py check
uv run python manage.py test events

The check reports no issues. The tests still fail as in Step 1, because no page extends the layout yet.

Step 3: Move the pages onto the layout

Common Error: a misspelled block name, or text outside a block

Neither raises an error. The page returns 200 with that content missing. If part of a page disappears, compare each block name with base.html and check that the content sits inside a block.

Replace events/templates/events/list.html with this complete file:

{% extends "base.html" %}

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

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

Replace events/templates/events/detail.html:

{% extends "base.html" %}

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

{% block content %}
  <h1>Sample: {{ title }}</h1>
  <p>This fictional event is an example.</p>
  <a href="{% url 'events:list' %}">All sample events</a>
{% endblock %}

The home page gets a template too. Create events/templates/events/home.html. It does not fill the title block, so the tab shows the fallback, Otahque:

{% extends "base.html" %}

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

In events/views.py, the home view now renders that template, so HttpResponse is no longer needed. Replace the file:

"""The events app's views: one function per page."""
from django.http import Http404
from django.shortcuts import render

SAMPLE_EVENTS = {1: 'Python meetup'}


def home(request):
    """Welcome visitors to Otahque."""
    return render(request, 'events/home.html')


def event_list(request):
    """List Otahque's events."""
    events = [
        {'id': event_id, 'title': title}
        for event_id, title in SAMPLE_EVENTS.items()
    ]
    return render(
        request, 'events/list.html', {'events': events}
    )


def event_detail(request, event_id):
    """Show one event, or 404 if its number is unknown."""
    title = SAMPLE_EVENTS.get(event_id)
    if title is None:
        raise Http404('Sample event not found')
    return render(
        request, 'events/detail.html', {'title': title}
    )

Run the tests again:

uv run python manage.py test events

Expected result, shortened:

Found 14 test(s).
System check identified no issues (0 silenced).
..FE.FFF...EE...
...
FAIL: test_pages_include_navigation (events.tests...
...
Ran 14 tests in ...

FAILED (failures=4, errors=3)

test_pages_extend_layout now passes: all three pages use the layout and their own titles. Navigation, the partial, and the filter remain.

Step 4: Add the navigation with include

Common Error: a tag placed before extends

{% extends %} must be the first template tag in a child. Putting {% load %} or any other tag above it raises a TemplateSyntaxError that ends {% extends "base.html" %} must be the first tag in 'events/list.html'. Plain text above it does not fail, but it is printed before the doctype, which is never what we want.

Create the folder templates/includes. In PowerShell:

New-Item -ItemType Directory -Force templates/includes

In a macOS shell or Linux/WSL Bash:

mkdir -p templates/includes

Create templates/includes/site_nav.html:

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

The aria-label gives screen readers a name for this navigation area. Now include it in the layout. Replace templates/base.html with this version, which adds one line after <body>:

<!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>
</head>
<body>
  {% include "includes/site_nav.html" %}
  <main>
    {% block content %}{% endblock %}
  </main>
</body>
</html>

Run the tests. test_pages_include_navigation now passes as well; the partial and filter tests still fail.

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

FAILED (failures=1, errors=3)

Step 5: Make the list row a partial

Common Error: an undefined partial name

{% partial row %} for a name that no partialdef defines fails with TemplateSyntaxError: Partial 'row' is not defined in the current template. Loading events/list.html#row from a view or test fails with TemplateDoesNotExist. Compare the name in both places, including hyphens.

Replace events/templates/events/list.html with this version. The list item is now wrapped in an inline partial named event-row:

{% extends "base.html" %}

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

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

Because the partial is inline, the page renders exactly as before. Run the tests; test_row_renders_alone now passes, and only the filter and the detail heading remain:

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

FAILED (failures=1, errors=2)

Step 6: Add the filter and restart the server

Common Error: load is not inherited, and a new module needs a restart

A child that uses sample_label without its own {% load event_labels %} raises a TemplateSyntaxError ending Invalid filter: 'sample_label', even if its parent loads the library. If the development server was running when you created templatetags, it may report 'event_labels' is not a registered tag library until you stop it and start it again.

Create the package folder events/templatetags and an empty __init__.py inside it, which makes the folder a Python package. In PowerShell:

New-Item -ItemType Directory -Force events/templatetags
New-Item -ItemType File events/templatetags/__init__.py

In a macOS shell or Linux/WSL Bash:

mkdir -p events/templatetags
touch events/templatetags/__init__.py

Create events/templatetags/event_labels.py:

"""Template filters and tags for event pages."""
from django import template
from django.utils.html import format_html

register = template.Library()


@register.filter
def sample_label(title):
    """Mark a title as fictional sample data, escaping it."""
    return format_html(
        '<span class="sample-label">Sample:</span> {}', title
    )

register is the library Django finds when a template says {% load event_labels %}; the module’s file name is the library’s name. @register.filter adds the function to it under its own name. format_html escapes title before putting it in place of {}.

Use the filter in both pages. Replace events/templates/events/list.html with its final version:

{% 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>
    {% for event in events %}
      {% partialdef event-row inline %}
        <li>
          <a href="{% url 'events:detail' event.id %}">
            {{ event.title|sample_label }}
          </a>
        </li>
      {% endpartialdef %}
    {% empty %}
      <li>No sample events yet.</li>
    {% endfor %}
  </ul>
{% endblock %}

Replace events/templates/events/detail.html. The heading no longer writes Sample: itself; the filter supplies it:

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

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

{% block content %}
  <h1>{{ title|sample_label }}</h1>
  <p>This fictional event is an example.</p>
  <a href="{% url 'events:list' %}">All sample events</a>
{% endblock %}

Each {% load %} comes after {% extends %}, never before it. Run the checks:

uv run python manage.py check
uv run python manage.py test events

Expected result, shortened; the dashed line is left out:

System check identified no issues (0 silenced).
Found 14 test(s).
System check identified no issues (0 silenced).
..............
Ran 14 tests in ...

OK

All 14 tests pass: the nine from Chapter 11, kept or updated, and five new ones. If the development server is running, stop it with Ctrl+C. Then start it again from the same directory:

uv run python manage.py runserver

Open http://127.0.0.1:8000/. The page shows the navigation and Welcome to Otahque. Follow Events, then Python meetup, and use Home and Events on each page to move around. The tab titles read Otahque, Sample events | Otahque, and Sample event | Otahque. Visit http://127.0.0.1:8000/events/999/ and confirm a 404. Stop the server with Ctrl+C. As before, do not apply migrations yet.

When something goes wrong

When the problem is inside a template file, Django starts a TemplateSyntaxError message with Template:, the file’s full path, and a comma. Table 12.2 leaves that part out and marks the gap with ...; the path tells you which file to open.

Table 12.2 — Template problems and safe recovery
Symptom Possible cause What to check
TemplateDoesNotExist: base.html DIRS was not changed, or the folder is misplaced DIRS reads [BASE_DIR / 'templates'] and templates/ sits beside manage.py
TemplateSyntaxError: ... {% extends "base.html" %} must be the first tag in 'events/list.html'. A tag sits above extends Move load and every other tag below extends
TemplateSyntaxError: ... 'block' tag with name 'content' appears more than once The same block name is used twice Keep one block of each name in a template
TemplateSyntaxError: ... Invalid filter: 'sample_label' The page did not load the library Add {% load event_labels %} below extends in that page
TemplateSyntaxError: ... 'event_labels' is not a registered tag library The module or package file is missing, misnamed, or new to a running server Check events/templatetags/__init__.py and event_labels.py, then restart runserver
TemplateSyntaxError: Partial 'row' is not defined in the current template. The partial name differs Compare the partialdef and partial names
Part of a page is missing, with no error A misspelled block name, or content outside a block Compare block names with base.html
An escaping test fails The filter or a template bypasses escaping Use format_html, and remove mark_safe or safe

Keep your work while you diagnose a problem. Compare the one file the 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 12.3 beside manage.py, with the development server running for the browser rows.

Table 12.3 — Verification checklist for Chapter 12
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 14 test(s). and OK at the end
Layout and navigation uv run python manage.py test events -k Layout Found 2 test(s). and OK at the end
Filter escaping uv run python manage.py test events -k escapes Found 3 test(s). and OK at the end
Home page Open http://127.0.0.1:8000/ Navigation and Welcome to Otahque.
Moving around Use Home and Events on each page Each link opens the expected page
Labelled sample Open the Python meetup detail Sample: Python meetup, as a heading
Missing event Open http://127.0.0.1:8000/events/999/ A 404 page

The escaping check finds three tests: the two from Chapter 11 and the filter’s own. Together with the partial test, they show that the title is escaped on every path we render it, in these templates. The official references for this chapter are https://docs.djangoproject.com/en/6.1/ref/templates/language/, https://docs.djangoproject.com/en/6.1/ref/templates/builtins/, and https://docs.djangoproject.com/en/6.1/howto/custom-template-tags/.

PAGE 004

Checkpoint: Quiz and Challenge

Quiz

Que. 3 What does a child template’s {% extends "base.html" %} tell Django?

Flip to check your answerFold answer back

Answer. To render base.html as the page, using the child’s blocks in place of the parent’s blocks with the same names.

Que. 4 A child fills a block named contnet. What happens?

Flip to check your answerFold answer back

Answer. Nothing visible and no error. The parent defines no such block, so its content is dropped. The page still returns 200, which is why our tests check for content.

Que. 5 What context does an included template see, and how can you limit it?

Flip to check your answerFold answer back

Answer. The same context as the template that includes it. with passes extra values, and only restricts it to those values.

Que. 6 What does inline add to {% partialdef %}?

Flip to check your answerFold answer back

Answer. It renders the partial where it is defined, as well as defining it. Without inline, nothing appears until {% partial %} uses it.

Que. 7 Why does sample_label use format_html instead of joining strings and calling mark_safe?

Flip to check your answerFold answer back

Answer. format_html escapes the title before inserting it and marks only the finished result safe. Joining first would mark an unescaped title safe and switch off the protection the escaping tests check.

Mini-Challenge

Work in a separate copy of your project, so your checkpoint stays as it is. Django also offers inclusion tags: a function that chooses context and renders its own small template, used as {% event_card event %}.

Que. 8 In the copy, add an event_card inclusion tag to event_labels.py that renders events/event_card.html with a linked, labelled title. Write a test first that renders the tag with a title containing <b> and checks the link and the escaped title.

Flip to check your answerFold answer back

Answer. The test renders a tiny template, as the filter tests do:

class EventCardTagTests(SimpleTestCase):
    """The event_card tag renders one card."""

    def test_card_links_and_escapes(self):
        template = Template(
            '{% load event_labels %}{% event_card event %}'
        )
        event = {'id': 1, 'title': '<b>Not a tag</b>'}
        html = template.render(Context({'event': event}))
        self.assertIn('href="/events/1/"', html)
        self.assertIn('&lt;b&gt;Not a tag', html)

Add the tag below the filter in event_labels.py:

@register.inclusion_tag('events/event_card.html')
def event_card(event):
    """Render one event as a card."""
    return {'event': event}

Create events/templates/events/event_card.html. It loads the library itself, because an inclusion tag’s template is rendered on its own:

{% load event_labels %}
<article>
  <a href="{% url 'events:detail' event.id %}">
    {{ event.title|sample_label }}
  </a>
</article>

The test fails until the tag and template exist, then all 15 tests in the copy pass. An inclusion tag suits a piece that needs its own context, used across many templates. Leave your main project at 14 tests for Chapter 13.

What We Learned

  • A base template holds the shared structure, and child templates fill its named blocks.
  • Inheritance mistakes such as a misspelled block are silent, so tests check content.
  • A project templates folder, found through DIRS, holds what no single app owns.
  • include inserts a self-contained template with the current context, limited by with and only.
  • A partial names a fragment inside one template and can be rendered alone with template#partial.
  • A custom filter that adds HTML uses format_html, so its input stays escaped.

Key terms

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

Table 12.4 — Key terms from Chapter 12
Term Meaning in this chapter
Base template A template holding the structure that pages share, with blocks.
Block A named place in a base template that a child may fill.
Child template A template that extends a base and supplies blocks.
Include Rendering another template at a point, with the current context.
Partial A named fragment inside a template, usable alone.
Custom filter A registered function applied to a value with a pipe.
format_html Builds HTML from a pattern and escapes each argument.

Readiness checkpoint: you are ready for Chapter 13 when all three pages show the navigation, each has its own tab title, the detail heading reads Sample: Python meetup, and all 14 tests pass. Explain why a misspelled block name needs a test to catch it. 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 templates events/views.py
git add events/tests.py events/templates events/templatetags
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 "Share one layout and navigation across pages"
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 choose between tools. L4 and L5 look ahead to a larger application and a code review: 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 the difference between extends and include?

What the interviewer is testing: Can you tell the outer structure of a page from a piece placed inside it?

Flip to check your answerFold answer back

Perfect answer: extends says this template is a variation of a parent: the parent is rendered as the page and the child only fills its blocks. include goes the other way: it inserts another template’s output at one point inside the current one. A page extends one layout at most, but it can include many pieces. In Otahque, every page extends base.html, and base.html includes the navigation.

Table 12.5 — extends compared with include
Question extends include
Direction The child fills its parent The current template inserts another
How many At most one, as the first tag Any number, anywhere
Context The child's blocks see the page context Sees the current context, unless only is used
Our example Each page extends base.html base.html includes site_nav.html

Behind the scenes:

# ExtendsNode: load the parent, collect the child's blocks
#     by name, and render the parent with them.
# IncludeNode: load another template and render it here
#     with the current context, or only the given values.

Code proof: list the templates used to render the event list:

uv run python manage.py shell -c "
from django.test import Client
from django.test.utils import setup_test_environment
setup_test_environment()
response = Client().get('/events/')
for name in sorted({t.name for t in response.templates}):
    print(name)
"
12 objects imported automatically (use -v 2 for details).

base.html
events/list.html
includes/site_nav.html

Common mistakes:

  • Using include for the outer layout, and repeating it in every page.
  • Placing a tag above extends.
  • Expecting a child’s text outside blocks to appear.

Follow-up the interviewer might ask:

  • “Can a base template itself extend another template?”
  • “When would you use include with only?”

L2 (Mid-Level): How does Django decide what a child page renders?

What the interviewer is testing: Can you trace blocks, fallbacks, and the silent cases?

Flip to check your answerFold answer back
Django reads extends and loads the parent, collects the child’s blocks by name, renders the parent from the top, uses the child’s block where one exists and the fallback where not, and drops everything else in the child.
Figure 12.3 — How a child’s blocks replace its parent’s.

Perfect answer: Django loads the parent named by extends, collects the child’s blocks by name, and renders the parent. At each block it uses the child’s version if there is one, otherwise the parent’s fallback; block.super inside a child’s block adds the fallback back. Everything else in the child is dropped: text outside blocks, and blocks the parent does not define. None of that raises an error, so I would test that each page shows its own content, not just that it returns 200.

Behind the scenes:

# BlockNode.render(): take the most specific version of
#     this block from the block context; block.super renders
#     the next version up the chain.

Code proof: render a child with a misspelled block and text outside blocks:

uv run python manage.py shell -c "
from django.template import engines
child = engines['django'].from_string(
    '{% extends layout %}outside'
    '{% block contnet %}typo{% endblock %}'
    '{% block title %}{{ block.super }} | Test{% endblock %}'
)
page = child.render({'layout': 'base.html'})
print('outside' in page, 'typo' in page)
print([x.strip() for x in page.splitlines() if 'title' in x])
"
12 objects imported automatically (use -v 2 for details).

False False
['<title>Otahque | Test</title>']

extends also accepts a variable, which the proof uses to avoid nested quotes in the shell.

Common mistakes:

  • Expecting an error for a misspelled block name.
  • Forgetting block.super and losing the parent’s content.
  • Defining the same block name twice.

Follow-up the interviewer might ask:

  • “What does a block nested inside another block do?”
  • “How would you test that every page fills the title block?”

L3 (Senior): When would you choose a partial, an include, or an inclusion tag?

What the interviewer is testing: Can you choose a reuse mechanism by who uses the piece and what context it needs?

Flip to check your answerFold answer back
Ask whether the piece is used by one template or several. One template: a partial. Several templates with the current context: an include. Several templates needing context of their own: an inclusion tag. Then test the piece alone.
Figure 12.4 — Choose a reuse mechanism.

Perfect answer: A partial, when the piece belongs to one template but is worth naming: it stays beside its use and can still be rendered alone, as our event row is in a test and, later, in a partial page update. An include, when several templates share a self-contained piece that works with the context it is given, such as the navigation; only keeps that dependency explicit. An inclusion tag, when the piece needs to prepare its own context and be called like a function from many templates. In every case I want a test that renders the piece alone.

Behind the scenes:

# A name such as 'events/list.html#event-row' loads the
#     template, then returns its partial 'event-row' as a
#     template of its own.

Code proof: render the event row alone, without the layout:

uv run python manage.py shell -c "
from django.template.loader import render_to_string
event = {'id': 1, 'title': 'Python meetup'}
row = render_to_string(
    'events/list.html#event-row', {'event': event}
)
for line in row.splitlines():
    if line.strip():
        print(line.strip())
"
12 objects imported automatically (use -v 2 for details).

<li>
<a href="/events/1/">
<span class="sample-label">Sample:</span> Python meetup
</a>
</li>

Common mistakes:

  • Moving every fragment into its own file before anything else needs it.
  • Letting an included template depend on variables it never states.
  • Rendering a partial alone without its own test.

Follow-up the interviewer might ask:

  • “What would change if two templates needed the event row?”
  • “Why might a server send just one row back to the browser?”

L4 (Staff): How would you organize templates across many apps?

What the interviewer is testing: Can you design template ownership and lookup for a growing project?

Flip to check your answerFold answer back
Put shared layout and includes in the project templates folder, keep each app’s pages in its own namespaced folder, search DIRS before app folders, and check which file each name resolves to.
Figure 12.5 — Organize templates by ownership.

Perfect answer: Shared structure, the base layout and site-wide includes, lives in the project templates folder found through DIRS. Each app keeps its own pages under a folder named after the app, such as events/templates/events/, so names never collide. Because DIRS is searched before app folders, a project template with the same name as an app’s would win, which is useful for deliberate overrides and confusing by accident; I would keep the names distinct and check origins when in doubt. Apps extend the shared layout instead of each keeping their own.

Behind the scenes:

# find_template(name): try each loader in order: the
#     filesystem loader searches DIRS, then the app
#     directories loader searches each app's templates.

Code proof: show which file each template name resolves to:

uv run python manage.py shell -c "
from pathlib import Path
from django.conf import settings
from django.template.loader import get_template
for name in ('base.html', 'events/list.html'):
    origin = get_template(name).origin
    path = Path(origin.name).relative_to(settings.BASE_DIR)
    print(name, '->', path.as_posix())
"
12 objects imported automatically (use -v 2 for details).

base.html -> templates/base.html
events/list.html -> events/templates/events/list.html

Common mistakes:

  • Putting the shared layout inside one app.
  • Leaving out the app-named folder, so names collide.
  • Overriding a template by accident because a name repeats.

Follow-up the interviewer might ask:

  • “How would you override a template from a third-party app?”
  • “Where would an email template live?”

L5 (Lead): A review finds mark_safe in a custom filter. How do you respond?

What the interviewer is testing: Can you review an escaping risk with evidence and a clear fix?

Flip to check your answerFold answer back
Find what the marked string contains, check whether any part comes from data, prove the risk with a test using an HTML-looking value, replace the join with format_html, and keep the test as a guard.
Figure 12.6 — Review a safe-marking filter.

Perfect answer: I would ask what is inside the string being marked safe. If any part comes from data, such as a title, the filter has switched off escaping for that data on every page that uses it. I would show it with a test that passes an HTML-looking value and expects it escaped, which fails. The fix is format_html, or conditional_escape on each input before joining, and the test stays as a regression guard. mark_safe on a fixed string with no data is fine; the review question is always where the data enters.

Behind the scenes:

# format_html(pattern, *args): escape each argument,
#     fill the pattern, and mark the result safe.
# mark_safe(text): mark the text safe exactly as it is.

Code proof: the same title through both approaches:

uv run python manage.py shell -c "
from django.utils.html import format_html
from django.utils.safestring import mark_safe
title = '<b>Not a tag</b>'
print(format_html('<span>Sample:</span> {}', title))
print(mark_safe('<span>Sample:</span> ' + title))
"
12 objects imported automatically (use -v 2 for details).

<span>Sample:</span> &lt;b&gt;Not a tag&lt;/b&gt;
<span>Sample:</span> <b>Not a tag</b>

The first line keeps the title as text; the second would put a real b element on the page. Rewriting our filter the second way makes four tests fail: the three escaping tests and the partial test, which renders an HTML-looking title too.

Common mistakes:

  • Approving mark_safe because the current data looks harmless.
  • Fixing the filter without adding a test that would catch it again.
  • Treating format_html as validation; it escapes, it does not check meaning.

Follow-up the interviewer might ask:

  • “How would you find every mark_safe in a large project?”
  • “When is mark_safe the right tool?”

Next: Chapter 13 introduces static files and CSS fundamentals.

PAGE 006