CHAPTER ELEVEN
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
Why This Matters
Soni can open the fictional sample event from Chapter 10, but the view returns one line of plain text. She wants a list that leads to a detail page, with headings that make the information easier to understand. We could assemble an HTML page inside each Python function, but the page structure would quickly become tangled with the decisions the view makes.
There is another problem: an event title is data. If a title contains characters that have meaning in HTML, a browser must not mistake that title for page markup. This chapter separates the page structure from its data and tests the boundary where the two meet. The events remain fictional, fixed in memory, and clearly labelled as examples.
By the end of the chapter, you will be able to:
- explain a template, context, and the rendered response;
- locate app-scoped templates and pass data from a view;
- show a sample list, an empty state, and a linked detail page;
- explain HTML autoescaping and its limits;
- write tests for the rendered template, a missing event, and escaped text.
We will use simple HTML and the existing sample data. Template inheritance, shared layouts, and styling come later. This chapter does not create stored events, accounts, forms, or published event records.
Found an error or something unclear? Report an issue with this chapter (GitHub, opens in a new tab)
PAGE 001What You Need to Know
HTML, templates, and context
In Chapter 3 we learned that a browser can interpret an HTML response as a page. HTML uses elements such as headings, paragraphs, lists, and links to describe structure. For example, an h1 element is a top-level heading; it is not just a way to make text large. A link’s href gives its destination. The browser reads the HTML and builds its own in-memory model of the page, called the DOM, short for document object model. So the raw HTML sent by the server and the text visible on the page are related but not identical, and that difference matters when we come to escaping.
New Concept: a template and its context
What problem exists? Our view needs to display data without constructing an entire HTML document in Python.
What did people do before? Programs joined strings by hand, which mixes page structure with application decisions and leaves every value to be escaped by remembering to do so.
What is a template? A file describing the output structure, with places for values and template instructions. Context is the collection of named values provided when the template is rendered.
Why templates? Page structure and application decisions can change separately, and Django escapes ordinary values on the way in.
Now let’s use it.
In a Django template, {{ title }} means “insert the value named title”. The braces belong to the template language and are not part of the displayed title. A tag such as {% for event in events %} controls rendering; {% empty %} provides an alternative when the collection has no items. The view chooses the data and calls render(request, template_name, context). Django loads the template, applies the context, and returns an HTML response.

Que. 1 Is the context itself an HTML page?
Flip to check your answerFold answer back
Answer. No. It supplies named values. The template provides the structure, and rendering combines them into a response.
Where Django finds a template
Our Chapter 10 settings already include the Django template backend and APP_DIRS set to True. With this configuration, Django can search the templates directory of an installed app. We will place our files inside events/templates/events/. The repeated events folder is deliberate: it makes names such as events/list.html less likely to collide with another app’s list.html.
Under the Hood: Loading and rendering
The view calls render() with the request, a template name, and a context dictionary. Django asks its configured template engine to find the named file. The engine evaluates its variables and tags using that context, then the shortcut returns an HttpResponse containing the result. A wrong path or missing file raises a template-not-found error. The exact search depends on the project’s template settings and installed apps.
The existing events:detail route accepts an event ID. The template’s {% url %} tag can build the address from that name and ID; it does not invent an event. If the name or required argument is wrong, rendering can fail. The list and detail templates use the same in-memory sample dictionary that the view checks. There is still no database.
Escaping data for HTML
In HTML, characters such as <, >, &, and quotes have special meanings. HTML escaping represents them in a way that allows the browser to display the characters as text in an appropriate HTML context. For example, <strong> in an ordinary title becomes escaped output; the browser displays the characters instead of making a strong element from that value.
Django’s template language automatically HTML-escapes ordinary variable values by default. This is an important protection against cross-site scripting, often shortened to XSS, where attacker-controlled content is made to run as code in someone else’s browser. It is not a guarantee that every output context is safe. Marking untrusted data as safe or disabling autoescaping can bypass this protection. HTML escaping alone does not validate a URL or provide the right handling for arbitrary JavaScript or CSS. Choose protections for the context, and validate data for its intended purpose.
In practice: a surprising title
Situation. A fictional sample title contains angle brackets that look like an HTML tag.
Application. The template renders the ordinary title as text using automatic escaping, so the browser shows the brackets instead of treating them as markup.
Consideration. The displayed text and the raw HTML differ, and neither this one example nor a passing test proves every context safe.
Que. 2 Why is it risky to apply safe to an untrusted title just because it contains markup?
Flip to check your answerFold answer back
Answer. It tells the template engine not to apply ordinary escaping to that value. The browser may then interpret the markup. Only use a safe-marking mechanism when the value has been made safe for its particular output context.
Found an error or something unclear? Report an issue with this chapter (GitHub, opens in a new tab)
PAGE 002How We Build It
Start from Chapter 10 in the directory containing manage.py, with your own .env, the locked environment, and six passing tests. We will change events/tests.py and events/views.py, then add events/templates/events/list.html and events/templates/events/detail.html. The existing events/urls.py remains in place. We add no dependency, migration, model, or external service.
The Custom Way
This illustration shows the problem; do not add it to the project or run it with untrusted data:
def unsafe_heading(title):
return '<h1>' + title + '</h1>'If title contains HTML-looking text, simple concatenation does not escape it. Writing the page this way would put the burden on us to handle each output context correctly. Our actual project uses Django’s template engine and keeps autoescaping enabled.
The Django Way
Step 1: Change the tests first
In events/tests.py, replace the file with the complete listing below. The Chapter 10 home, route, and 404 checks remain. The list and detail assertions change because these responses will now be HTML rather than the old placeholder and plain-text result. patch.dict temporarily changes the sample dictionary inside one test and restores it afterwards; it does not change your project file.
"""Tests for the events app."""
from unittest.mock import patch
from django.test import SimpleTestCase
from django.urls import resolve, reverse
from . import views
class RoutingTests(SimpleTestCase):
"""Each address reaches its view; others are not found."""
def test_home(self):
response = self.client.get('/')
self.assertContains(
response, 'Welcome to Otahque.'
)
self.assertEqual(reverse('events:home'), '/')
self.assertIs(resolve('/').func, views.home)
def test_event_list(self):
response = self.client.get('/events/')
self.assertContains(response, 'Python meetup')
self.assertTemplateUsed(
response, 'events/list.html'
)
self.assertContains(
response, 'href="/events/1/"'
)
self.assertEqual(
reverse('events:list'), '/events/'
)
self.assertIs(
resolve('/events/').func, views.event_list
)
def test_unknown_path(self):
response = self.client.get('/does-not-exist/')
self.assertEqual(response.status_code, 404)
class EventDetailTests(SimpleTestCase):
"""One event by number, and the 404 for any other."""
def test_sample_event(self):
response = self.client.get('/events/1/')
self.assertContains(
response, 'Sample: Python meetup'
)
self.assertTemplateUsed(
response, 'events/detail.html'
)
self.assertTrue(
response['Content-Type'].startswith(
'text/html'
)
)
def test_missing_event(self):
self.assertIs(
resolve('/events/999/').func,
views.event_detail,
)
response = self.client.get('/events/999/')
self.assertEqual(response.status_code, 404)
def test_invalid_id(self):
response = self.client.get('/events/abc/')
self.assertEqual(response.status_code, 404)
class TemplateSafetyTests(SimpleTestCase):
"""Templates escape titles; an empty list says so."""
def test_empty_list(self):
with patch.dict(
views.SAMPLE_EVENTS, {}, clear=True
):
response = self.client.get('/events/')
self.assertContains(
response, 'No sample events yet.'
)
def test_list_escapes_title(self):
title = '<strong>Not a tag</strong>'
with patch.dict(
views.SAMPLE_EVENTS, {1: title}, clear=True
):
response = self.client.get('/events/')
self.assertContains(
response, '<strong>'
)
self.assertNotContains(
response, '<strong>Not a tag'
)
def test_detail_escapes_title(self):
title = '<strong>Not a tag</strong>'
with patch.dict(
views.SAMPLE_EVENTS, {1: title}, clear=True
):
response = self.client.get('/events/1/')
self.assertContains(
response, '<strong>'
)
self.assertNotContains(
response, '<strong>Not a tag'
)Run this command beside manage.py in PowerShell, a macOS shell, or Linux/WSL Bash:
uv run python manage.py test eventsExpected result, shortened with ... where lines are left out:
Found 9 test(s).
System check identified no issues (0 silenced).
..FF..FFF
...
FAIL: test_sample_event (events.tests.EventDetailTests...
...
FAIL: test_event_list (events.tests.RoutingTests...
...
FAIL: test_detail_escapes_title (events.tests...
...
FAIL: test_empty_list (events.tests...
...
FAIL: test_list_escapes_title (events.tests...
...
Ran 9 tests in ...
FAILED (failures=5)Five tests fail, each for the reason we expected: the views still return the Chapter 10 text, with no template, no empty message, and no escaping. The four that pass cover the behaviour that must not change: the home page, the unknown path, the missing event, and the invalid ID. Read the failures, then continue. This is a deliberate starting check, not an instruction to leave the project failing.
Step 2: Write the views
Replace events/views.py with the complete file below. The home view stays as it was. The list view transforms the fixed dictionary into a list of dictionaries, each with an ID and title, and passes it as events. The detail view still raises Http404 for an unknown ID; for an existing one it passes title to its template.
"""The events app's views: one function per page."""
from django.http import Http404, HttpResponse
from django.shortcuts import render
SAMPLE_EVENTS = {1: 'Python meetup'}
def home(request):
"""Welcome visitors to Otahque."""
return HttpResponse('Welcome to Otahque.')
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}
)The values inside SAMPLE_EVENTS are deliberately fictional and live only in the Python process. The render() shortcut constructs the HTML response. The context keys, events and title, must agree with the names in the templates.
Step 3: Add the sample list template
The templates need a folder inside the app. Create it in your editor, or with a command. In PowerShell, beside manage.py:
New-Item -ItemType Directory -Force events/templates/eventsIn a macOS shell or Linux/WSL Bash, beside manage.py:
mkdir -p events/templates/eventsCreate list.html inside that inner folder and enter this complete file:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport"
content="width=device-width, initial-scale=1">
<title>Sample events | Otahque</title>
</head>
<body>
<main>
<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>
</main>
</body>
</html>The {% for %} tag repeats the list item for each event. The {% empty %} branch displays a message when there are none. The {% url %} tag uses the existing events:detail route and the current event’s ID. The browser sees a link; Django still checks the ID when its destination is requested.
Step 4: Add the detail template
Create events/templates/events/detail.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport"
content="width=device-width, initial-scale=1">
<title>Sample event | Otahque</title>
</head>
<body>
<main>
<h1>Sample: {{ title }}</h1>
<p>This fictional event is an example.</p>
<a href="{% url 'events:list' %}">All sample events</a>
</main>
</body>
</html>The title is inserted as an ordinary template variable in an HTML heading. The link uses the existing events:list name. Both pages label their data fictional. We keep their small repeated HTML structures for now; Chapter 12 will introduce inheritance and shared layouts.
Common Error: TemplateDoesNotExist
Check both events folder names and the filename. The view asks for events/list.html, while the file is inside the installed app at events/templates/events/list.html. Compare the path before creating or replacing anything else.
A misspelled variable is harder to notice, because it raises no error at all. {{ titel }} simply renders as nothing, and the heading reads Sample: with no title. That is one reason our tests look for the title itself, and not only for a 200 status.
Step 5: Run the checks and view the pages
In PowerShell, a macOS shell, or Linux/WSL Bash, beside manage.py:
uv run python manage.py check
uv run python manage.py test eventsExpected result, shortened; the dashed line is left out:
System check identified no issues (0 silenced).
Found 9 test(s).
System check identified no issues (0 silenced).
...
Ran 9 tests in ...
OKThese SimpleTestCase tests do not require a database. The escaping tests use a harmless title that looks like a strong tag; they check that its angle brackets are escaped in the response.
Start the local server from the same directory:
uv run python manage.py runserverOpen http://127.0.0.1:8000/events/, select Python meetup, and confirm the detail page says Sample: Python meetup. Visit http://127.0.0.1:8000/events/999/ and confirm a 404. Stop the server with Ctrl+C. Django may warn about unapplied migrations; do not apply them yet, because the custom user model is planned first. The test client checks responses, while a browser also lets you inspect the page and links.
When something goes wrong
| Symptom | Possible cause | What to check |
|---|---|---|
| TemplateDoesNotExist: events/list.html | The file is in the wrong folder | Compare both events folder names and the requested template name |
| NoReverseMatch while rendering | The route name or ID is wrong | Check events:detail and the event ID supplied to the url tag |
| A blank title, with no error | The context and variable names differ | Compare the context dictionary with the template variable |
| Chapter 10 assertions fail on text | events/tests.py was not replaced | Compare it with the complete Chapter 11 listing |
| An escaping test fails | Escaping is bypassed, or the output changed | Remove unsafe changes and compare the ordinary variable with the listing |
| ImproperlyConfigured: Set DJANGO_SECRET_KEY; see .env.example. | The Chapter 8 .env is missing | See Table 8.4. Never share the secret |
Keep your work while you diagnose a problem. Compare each named file to the listing and save a separate copy before replacing anything you want to keep. Fix one issue and rerun the tests. Do not delete the project or reset Git as a first response.
Found an error or something unclear? Report an issue with this chapter (GitHub, opens in a new tab)
PAGE 003Verify Your Work
Run the checks in Table 11.2 beside manage.py, with the development server running for the browser rows.
| 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 9 test(s). and OK at the end |
| Escaping | uv run python manage.py test events -k escapes | Found 2 test(s). and OK at the end |
| Empty list | uv run python manage.py test events -k empty | Found 1 test(s). and OK at the end |
| Sample list | Open http://127.0.0.1:8000/events/ | The fictional sample and its link appear |
| Sample detail | Follow the Python meetup link | Sample: Python meetup, as a heading |
| Missing event | Open http://127.0.0.1:8000/events/999/ | A 404 page |
-k runs only the tests whose names contain the given text.
An escaped response and a browser inspection provide evidence for the tested HTML text context, not every use of data in a future application. The official Django references are https://docs.djangoproject.com/en/6.1/topics/templates/ and https://docs.djangoproject.com/en/6.1/ref/templates/language/.
Found an error or something unclear? Report an issue with this chapter (GitHub, opens in a new tab)
PAGE 004Checkpoint: Quiz and Challenge
Quiz
Que. 3 What is the difference between a template and context?
Flip to check your answerFold answer back
Answer. A template describes output structure and instructions. Context supplies the named values used during rendering.
Que. 4 Why is the app name repeated in events/templates/events/list.html?
Flip to check your answerFold answer back
Answer. The inner folder is part of the template name, events/list.html, and helps distinguish it from similarly named templates in other apps.
Que. 5 What does {% empty %} do in the list template?
Flip to check your answerFold answer back
Answer. It supplies output for a for loop when the iterable contains no items.
Que. 6 Does HTML autoescaping make an arbitrary URL or JavaScript snippet safe?
Flip to check your answerFold answer back
Answer. No. HTML escaping is not a substitute for URL validation or the right handling for JavaScript and other output contexts.
Que. 7 Why did the Chapter 10 text assertions need to change?
Flip to check your answerFold answer back
Answer. The list and detail now return HTML from templates rather than the old placeholder and plain-text response. We retain tests for their routes and missing-event behaviour.
Mini-Challenge
Empty the sample list in a separate copy of the project, so that your own checkpoint stays as it is. Work it out before reading the model answer.
Que. 8 In a separate project copy, temporarily make SAMPLE_EVENTS an empty dictionary. What should /events/ show, and what should /events/1/ return? Restore the sample afterwards.
Flip to check your answerFold answer back
Answer. The list should show the message No sample events yet. The detail route still matches /events/1/, but the view finds no entry and returns 404 via Http404. Restore the sample dictionary and rerun uv run python manage.py test events so the next chapter starts at the documented checkpoint.
What We Learned
- A view supplies a template and context to produce an HTML response.
- App-scoped template names help distinguish files from different apps.
- Tags can render a list, an empty case, and links using named routes.
- Automatic HTML escaping protects ordinary variable output in the appropriate context, with limits.
- Tests check observed responses; browser inspection checks the rendered page and links.
Key terms
Use Table 11.3 to explain templates and escaping in your own words.
| Term | Meaning in this chapter |
|---|---|
| Template | A file describing output structure and rendering instructions. |
| Context | Named values supplied to a template when rendering. |
| Template tag | A template-language instruction such as a loop or URL lookup. |
| Autoescaping | Automatic escaping of ordinary values for HTML output by default. |
| XSS | Cross-site scripting: attacker-controlled code running in a site's context. |
| DOM | Document object model: the browser's in-memory model of a page. |
Readiness checkpoint: you are ready for Chapter 12 when the sample list links to the detail, an absent ID returns 404, and all nine tests pass. Explain what the escaping tests do and what they do not establish. Return to the relevant part if any result is missing.
Git Commit
After checking the changes, stage the four 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 events/tests.py events/views.py
git add events/templates/events/list.html
git add events/templates/events/detail.html
git diff --cachedKeep .env and its secret out of Git. Then record the commit. It stays on your computer; no remote push is needed:
git commit -m "Render sample event templates"Found an error or something unclear? Report an issue with this chapter (GitHub, opens in a new tab)
PAGE 005Test Your Knowledge: Interview Questions
These five questions rehearse the chapter at interview level, one at each of five levels from junior to lead. L1 and L2 check what you have just learned. L3 asks how to test it. L4 and L5 look ahead to a larger application’s design and evidence: attempt them now, and return to them when you reach those chapters. 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 does a template do?
What the interviewer is testing: Can you distinguish structure from the values supplied by a view?
Flip to check your answerFold answer back
Perfect answer: A template describes the output structure and holds variables and instructions. A view chooses the data and passes it as context, and the template engine combines the two into a response. Keeping them apart means a page’s structure can change without touching the view’s decisions. A template sees only what it is given: a view’s local variables reach it only through the context.
| Part | Its job |
|---|---|
| View | Decides what to show, and chooses the template and context |
| Context | Holds the named values for this one rendering |
| Template | Describes the structure, with places for those values |
Behind the scenes:
# render(request, name, context):
# html = loader.render_to_string(name, context, request)
# return HttpResponse(html)Code proof: render the detail template directly, then print its heading line:
uv run python manage.py shell -c "
from django.template.loader import render_to_string
page = render_to_string(
'events/detail.html', {'title': 'Python meetup'}
)
print([x.strip() for x in page.splitlines() if 'h1' in x])
"12 objects imported automatically (use -v 2 for details).
['<h1>Sample: Python meetup</h1>']Common mistakes:
- Calling the context an HTML page.
- Assuming a template can read a view’s local variables.
- Putting decisions in the template that belong in the view.
Follow-up the interviewer might ask:
- “Can a context contain a list?”
- “What does a template show for a name the context lacks?”
L2 (Mid-Level): How does Django find an app template?
What the interviewer is testing: Can you trace a template name to the configured loader and file?
Flip to check your answerFold answer back

Perfect answer: Our settings use the Django template backend with APP_DIRS set to True, so the engine searches the templates folder of each installed app, in INSTALLED_APPS order, and uses the first match. The name events/list.html therefore points to events/templates/events/list.html. The repeated folder is a namespace: templates from every app share one search, so another app’s list.html could otherwise be found instead of ours, with no error to warn us.
Behind the scenes:
# Loader.get_dirs(): the templates folder of each installed
# app, in order. get_template(name) tries each folder in
# turn, and raises TemplateDoesNotExist if none has it.Code proof: ask the engine which file a name leads to:
uv run python manage.py shell -c "
from pathlib import Path
from django.conf import settings
from django.template.loader import get_template
origin = get_template('events/list.html').origin
print(origin.template_name)
path = Path(origin.name).relative_to(settings.BASE_DIR)
print(path.as_posix())
"12 objects imported automatically (use -v 2 for details).
events/list.html
events/templates/events/list.htmlCommon mistakes:
- Leaving out the inner app-named folder.
- Forgetting that the app must be in
INSTALLED_APPS. - Assuming every project’s loader configuration is the same.
Follow-up the interviewer might ask:
- “What happens if two apps both provide
events/list.html?” - “When would a project-level template folder be useful?”
L3 (Senior): How would you test an empty list?
What the interviewer is testing: Can you control inputs and check observable output without permanently changing the project?
Flip to check your answerFold answer back

Perfect answer: Supply an empty collection in an isolated test, request the page, and assert that the empty-state message appears. Then make sure the sample state is restored, even if the test fails, so that other tests are not affected by the order they run in. patch.dict used as a context manager does all of that for us. A 200 status alone would prove little here, because a blank page also returns 200, so the assertion must be on the message itself.
Behind the scenes:
# patch.dict(target, values, clear=True): on entering, copy
# target, then empty and fill it. On leaving, even after
# an exception, restore the copy.Code proof: run only that test by name:
uv run python manage.py test events -k test_empty_listFound 1 test(s).
System check identified no issues (0 silenced).
...
Ran 1 test in ...
OKCommon mistakes:
- Deleting real data to simulate an empty state.
- Checking only a 200 status.
- Leaving shared state changed, so that a later test fails for no visible reason.
Follow-up the interviewer might ask:
- “Does this test a database query?”
- “How would this test change once events are stored?”
L4 (Staff): What are the limits of HTML autoescaping?
What the interviewer is testing: Can you reason about untrusted data and output contexts?
Flip to check your answerFold answer back

Perfect answer: Ordinary template variables are HTML-escaped by default, which stops a value from becoming markup in HTML text. That protection can be switched off by safe and by disabling autoescaping, so those need review wherever they appear. It is also limited to what it does. Escaping changes < and &, not the meaning of a value, so a javascript: address passes through untouched, and a link built from it can still run code. So a URL must be validated for its purpose, and data for JavaScript or CSS needs handling suited to that context. I would keep autoescaping on, restrict safe by code review, and test the contexts we actually use.
Behind the scenes:
# render_value_in_context(value, context):
# if context.autoescape and value is not marked safe:
# return conditional_escape(value)
# return valueCode proof: the same engine, three values:
uv run python manage.py shell -c "
from django.template import Context, Template
def show(source, value):
context = Context({'value': value})
print(Template(source).render(context))
show('{{ value }}', '<b>Sample</b>')
show('{{ value|safe }}', '<b>Sample</b>')
show('{{ value }}', 'javascript:alert(1)')
"12 objects imported automatically (use -v 2 for details).
<b>Sample</b>
<b>Sample</b>
javascript:alert(1)Common mistakes:
- Applying
safeto untrusted input. - Claiming one escaping rule secures every context.
- Treating an escaped value as validated.
Follow-up the interviewer might ask:
- “What else would you do for a link that members can supply?”
- “How would you find every use of
safein a large project?”
L5 (Lead): What does an escaping test prove?
What the interviewer is testing: Can you explain the strength and boundary of the evidence?
Flip to check your answerFold answer back

Perfect answer: It proves that this value is escaped on this rendering path, in these two templates. It guards against a specific regression, such as someone adding safe to the title. It does not prove that every future template, data source, browser, or output context is safe, and it is not a security certification. So I would report it in exactly those terms, keep it as a regression test, and revisit the risk when real user data arrives, because that is when the threat changes. A reviewer should be able to see both what was tested and what was not.
Behind the scenes:
# assertContains(response, '<strong>'): the escaped
# form is in the response.
# assertNotContains(response, '<strong>Not a tag'): the raw
# form is not. Each alone would prove less.Code proof: run only the two escaping tests:
uv run python manage.py test events -k escapesFound 2 test(s).
System check identified no issues (0 silenced).
...
Ran 2 tests in ...
OKCommon mistakes:
- Treating one test as a security certification.
- Testing only a successful status, not the rendered content.
- Checking for the escaped form without also checking that the raw form is absent.
Follow-up the interviewer might ask:
- “What changes when data comes from users?”
- “Which change to the template would make this test fail?”
Next: Chapter 12 introduces template inheritance, includes, and partials.
Found an error or something unclear? Report an issue with this chapter (GitHub, opens in a new tab)
PAGE 006Found an error or something unclear? Report an issue with this chapter (GitHub, opens in a new tab)