ContentsClose contents
Pre-release
Chapter 10 · Function-based views and request/response objectsCHAPTER 10

Complete six-part pre-release for review. The detail view uses fixed sample data; no event database exists yet.

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 TEN

Function-based views and request/response objects

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

Prerequisites: Chapters 3, 6, 8, and 9, including the Chapter 9 project and its passing tests

What you’ll build: a view that shows a fictional sample event or returns 404 when the requested sample is missing.

Why This Matters

Soni opens the event list that we introduced in Chapter 9. It is still a placeholder, so she cannot yet inspect an individual event. We can give her one small, controlled example: an address for a fictional Python meetup, with a clear label saying that it is sample data. There is no event database yet and nobody has published an event through Otahque.

The new address is only the beginning. Django must receive a request, choose a view, pass it the event number, and send back the response the view creates. What if the number is valid in the address but there is no sample event with that number? A useful application must explain that the requested item was not found, rather than quietly showing the wrong event.

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

  • explain how a function-based view receives a request and returns a response;
  • identify a request method, path, query string, response status, body, and content type;
  • pass a captured integer from a URL pattern to a view;
  • return a controlled sample event and raise Http404 when it is missing;
  • write and run tests for successful and unsuccessful requests.

Our sample is fixed in Python memory. Real event records, templates, forms, and account permissions arrive later; the wider styled-page milestone is not complete here.

PAGE 001

What You Need to Know

From a request to a response

In Chapter 3, a browser sent an HTTP request and received an HTTP response. Chapter 9 connected a path to a view. A function-based view is an ordinary Python function that Django calls for a request. Django supplies a request object as the first argument, usually named request. The view returns a response object, or raises an exception that Django handles, such as Http404.

New Concept: request and response objects

What problem exists? A view needs information about what was requested, and a way to send a result back.

What did people do before? Without a framework, a program parsed the incoming HTTP message and assembled the outgoing one itself.

What are they? HttpRequest describes an incoming request, and HttpResponse represents an outgoing response. Both are ordinary Python objects.

Why these objects? Django builds the request and sends the response, so application code can concentrate on the decision it needs to make.

Now let’s use it.

The request’s method describes the operation requested, such as GET. Its path identifies the requested path, for example /events/1/. Query parameters follow ? in the address and are available through request.GET; they are separate from the path. The name GET here is historical: query parameters can exist on requests using other methods too. Treat request values as untrusted input.

A response carries a status code, headers, and a body. Status 200 means the request succeeded; 404 says the requested resource was not found. The Content-Type header tells the recipient what kind of content the body contains. In this chapter the detail view returns text/plain, so our fixed sample title is shown as text. A response is not the same as printing a message in the server terminal.

A browser sends a request with a path and method. Django resolves the path, calls a view with the request and event number, then sends the view’s status, headers and body back to the browser.
Figure 10.1 — A view connects the incoming request to an outgoing response.

You can see these fields without changing the project. RequestFactory builds a request object for testing, so nothing needs a server or a browser. Beside manage.py, in PowerShell, a macOS shell, or Linux/WSL Bash:

uv run python manage.py shell -c "
from django.http import HttpResponse
from django.test import RequestFactory
request = RequestFactory().get('/events/1/?ref=list')
print(request.method, request.path)
print(request.GET['ref'])
response = HttpResponse('Hello')
print(response.status_code, response['Content-Type'])
print(response.content)
"

Expected result:

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

GET /events/1/
list
200 text/html; charset=utf-8
b'Hello'

The query string is not part of the path, and the response body is bytes, because that is what travels over the network. A response is text/html unless a view says otherwise, which is why our detail view will ask for plain text explicitly.

Que. 1 Does request.GET mean that the request method must be GET?

Flip to check your answerFold answer back

Answer. No. request.GET contains query parameters from the URL. A request using another method can also have a query string. request.method tells you the method.

A number in the path

In Chapter 9, both routes had fixed paths. To identify a particular sample event, we will add a pattern containing <int:event_id>. Django’s integer converter accepts a matching sequence of digits and passes its value as a Python integer in the event_id argument. A path such as /events/1/ matches the pattern; /events/abc/ does not. The converter checks the shape of the path, not whether an event with that number exists.

Under the Hood: From path to function argument

Django checks the project URLconf, follows its include into the events URLconf, and finds a matching detail pattern. The converter turns the captured digits into an integer and Django calls the view with request and the named event_id. The view looks up that number in our fixed dictionary. It returns a response for an existing sample or raises Http404 for a missing sample. Django turns the latter into a 404 response.

An unmatched path and a missing event can both produce 404, but the cause differs. For /events/abc/, the integer route does not match. For /events/999/, the route matches and the view finds no such sample. With DEBUG=True, Django’s diagnostic page may show development details; its exact appearance is not our production error page.

Que. 2 Does a successful integer conversion prove that the event exists?

Flip to check your answerFold answer back

Answer. No. It proves that this part of the path has the required shape. The view still needs to check the available data.

Fixed data, not user-supplied HTML

Our dictionary will hold one fictional title under the integer key 1. It is recreated when the Python process starts; it is not a database and does not persist edits. We return only the fixed title as plain text. Do not use this example as permission to insert untrusted values into HTML. Chapter 11 introduces templates and escaping, which help handle data safely in HTML; validation and other protections still matter.

In practice: a missing sample

Situation. Soni opens an address for a sample event that does not exist.

Application. The view checks the dictionary and raises Http404 when no entry is found, so she sees a not-found response instead of the wrong event.

Consideration. A real event page will need a reliable data source and its own access and publication rules; this sample establishes none of them.

PAGE 002

How We Build It

Start from the Chapter 9 project in the directory containing manage.py, with your own .env, the locked environment, and the three existing routing tests passing. We will change events/tests.py, events/views.py, and events/urls.py. No package, model, migration, or database is added. The result is a plain-text sample at /events/1/ and a 404 for a missing sample.

The Custom Way

Before using Django’s request handling, consider this small illustration. Do not add it to the project: it has no HTTP server and does not construct Django responses.

def choose_sample(event_id):
    if event_id == 1:
        return 'Sample: Python meetup'
    return 'not found'

The decision is straightforward, but returning the words not found alone does not make an HTTP response have status 404. Django supplies request and response objects and handles Http404 for us.

The Django Way

Step 1: Write the tests first

Open events/tests.py. Keep the entire RoutingTests class from Chapter 9. Add this new class after it, with two blank lines separating the classes:

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.assertEqual(response.status_code, 200)
        self.assertContains(
            response, 'Sample: Python meetup'
        )
        self.assertTrue(
            response['Content-Type'].startswith('text/plain')
        )

    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)

In PowerShell, a macOS shell, or Linux/WSL Bash, from the folder containing manage.py:

uv run python manage.py test events

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

Found 6 test(s).
System check identified no issues (0 silenced).
.EF...
...
ERROR: test_missing_event (events.tests.EventDetailTests...
...
django.urls.exceptions.Resolver404: ...
...
FAIL: test_sample_event (events.tests.EventDetailTests...
...
AssertionError: 404 != 200
...
Ran 6 tests in ...

FAILED (failures=1, errors=1)

.EF... reports the six tests in order. The E is new: test_missing_event stopped with an unexpected error, because its first line asks Django to resolve a route that does not exist yet. The F is the sample test receiving a 404. The invalid address already passes, because the URL dispatcher answers it. That first check in test_missing_event matters later: once the route exists, it shows that this test’s 404 comes from the view, not from a missing route. Read the failures, then continue; do not delete the tests.

Step 2: Write the view

Common Error: returning a string

A view must return a response object, not a Python string. return 'Sample' fails with AttributeError: 'str' object has no attribute 'get', which names neither the view nor the mistake, because the error appears later, when Django’s middleware handles the value. Forgetting return altogether gives a clearer message: The view events.views.event_detail didn't return an HttpResponse object.

Replace events/views.py with this complete file. The first two views are unchanged. The dictionary contains one controlled sample; .get() returns None when its key is missing.

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

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."""
    return HttpResponse('Event list coming soon.')


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 HttpResponse(
        f'Sample: {title}', content_type='text/plain'
    )

The f-string combines a fixed prefix and a title from our own fixed dictionary. The view does not place the request path or query string into the body. Setting content_type makes this example plain text; it does not make later HTML interpolation safe.

Step 3: Connect the detail route

Replace events/urls.py with the complete file below. Keep the existing namespace and both existing patterns. The argument name in the route, event_id, must match the view’s parameter name.

"""Addresses of the events app's pages."""
from django.urls import path

from . import views

app_name = 'events'

urlpatterns = [
    path('', views.home, name='home'),
    path('events/', views.event_list, name='list'),
    path('events/<int:event_id>/', views.event_detail,
         name='detail'),
]

Step 4: Run and inspect

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

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 6 test(s).
System check identified no issues (0 silenced).
...
Ran 6 tests in ...

OK

No database is required for these SimpleTestCase tests. The test client is useful, but it is not a browser and does not prove the page’s visual presentation.

Start the local server in the same folder and shells:

uv run python manage.py runserver

Visit http://127.0.0.1:8000/events/1/ and expect Sample: Python meetup. Visit http://127.0.0.1:8000/events/999/ and expect 404. Visit http://127.0.0.1:8000/events/abc/ and expect 404 from an unmatched route. Stop the server with Ctrl+C. If Django warns about unapplied migrations, do not apply them here; the planned custom user comes first.

When something goes wrong

Table 10.1 — View problems and safe recovery
Symptom Possible cause What to check
Tests fail to start, with a traceback Import or syntax error Read the traceback and compare the changed file with its listing
/events/1/ is 404 The detail route is absent, or key 1 is missing Check the route in events/urls.py and the key in SAMPLE_EVENTS
TypeError: event_detail() got an unexpected keyword argument The route and parameter names differ Use event_id in both the route and the view
AttributeError: 'str' object has no attribute 'get' The view returned a string Return HttpResponse, or raise Http404
ValueError: The view ... didn't return an HttpResponse object. The view has no return on some path Check that every path returns or raises
test_missing_event fails with 200 != 404 The missing lookup is not handled Check the None case and raise Http404
ImproperlyConfigured: Set DJANGO_SECRET_KEY; see .env.example. The Chapter 8 .env is missing See Table 8.4. Do not disclose the secret

Preserve your work while diagnosing a failure. Compare the three files with the listings and save a separate copy before replacing anything. Correct one problem, then rerun the full test suite. Do not reset Git or delete your project.

PAGE 003

Verify Your Work

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

Table 10.2 — Verification checklist for Chapter 10
Check Command or action Expected result
System check uv run python manage.py check System check identified no issues (0 silenced).
All route and view tests uv run python manage.py test events Found 6 test(s). and OK at the end
Existing sample Open http://127.0.0.1:8000/events/1/ Sample: Python meetup, as plain text
Missing sample Open http://127.0.0.1:8000/events/999/ A 404 page that names the detail view
Invalid identifier Open http://127.0.0.1:8000/events/abc/ A 404 page listing the patterns tried
Earlier pages Open http://127.0.0.1:8000/ and /events/ The Chapter 9 text remains

The tests exercise the two responses and retain Chapter 9’s checks. A test can fail for several reasons, so read the failure and traceback before deciding what to fix. For the official references, see https://docs.djangoproject.com/en/6.1/topics/http/views/ and https://docs.djangoproject.com/en/6.1/ref/request-response/.

PAGE 004

Checkpoint: Quiz and Challenge

Quiz

Que. 3 What is the difference between request.path and request.GET?

Flip to check your answerFold answer back

Answer. request.path is the requested path. request.GET contains query parameters supplied in the URL, regardless of the request method.

Que. 4 What does <int:event_id> provide to the view?

Flip to check your answerFold answer back

Answer. For a matching path it supplies the captured digits as an integer named event_id. It does not prove that a corresponding event exists.

Que. 5 What is the difference between printing a string and returning an HttpResponse?

Flip to check your answerFold answer back

Answer. Printing writes to the server’s output. Returning HttpResponse gives Django a response to send for the request.

Que. 6 Why can both /events/999/ and /events/abc/ return 404 for different reasons?

Flip to check your answerFold answer back

Answer. The integer route matches 999 and the view raises Http404 for the absent sample. The route does not match abc, so no detail view is selected for that path.

Que. 7 Does this plain-text sample establish safe HTML rendering for arbitrary input?

Flip to check your answerFold answer back

Answer. No. It uses fixed sample data and returns plain text. HTML and untrusted data require appropriate escaping and other controls, introduced as the application develops.

Mini-Challenge

Add a second sample 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 copy of the project, add key 2 with the fictional title Django workshop to SAMPLE_EVENTS. What should /events/2/ return? How can you check that an absent sample still produces 404?

Flip to check your answerFold answer back

Answer. With the local server running, /events/2/ should return Sample: Django workshop as plain text. Run uv run python manage.py test events to retain the existing missing-event check, and visit /events/999/ if checking in a browser. Remove the temporary entry or keep the exercise in a separate copy so the next chapter starts from the documented checkpoint.

What We Learned

  • A function-based view receives a request and returns an HTTP response or raises a handled exception.
  • The URL converter passes a matching integer to the view; it does not check the sample dictionary.
  • The response has a status, headers, and a body; our sample is explicit plain text.
  • A missing item and an unmatched route can both produce 404 for different reasons.
  • Tests and browser checks offer complementary evidence.

Key terms

Use Table 10.3 to explain requests, responses, and not-found handling in your own words.

Table 10.3 — Key terms from Chapter 10
Term Meaning in this chapter
Function-based view A Python function Django calls to handle a request.
HttpRequest An object describing the incoming request.
HttpResponse An object describing the outgoing response.
Path converter A route component that matches and converts part of a path.
Http404 An exception Django turns into a not-found response.
Content-Type A response header describing the body format.
RequestFactory A test tool that builds request objects without a client or a server.

Readiness checkpoint: you are ready for Chapter 11 when the sample detail page shows the expected text, missing and invalid addresses return 404, and all six tests pass. Explain which 404 comes from the view and which from routing, and what E means in a test run. Return to the relevant part if any result is missing.

Git Commit

When the checks pass, see what changed and stage the three 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 events/urls.py
git diff --cached

Keep your .env and its secret out of Git. Then record the commit. It stays on your computer; there is no remote push in this chapter:

git commit -m "Add sample event detail view"
PAGE 005

Test Your Knowledge: Interview Questions

These five questions rehearse the chapter at interview level, one at each of five levels from junior to lead. L1 and L2 check what you have just learned. L3 asks how it works underneath. L4 and L5 look ahead to decisions a larger application must make: 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 function-based view do?

What the interviewer is testing: Can you describe the request and response contract in plain language?

Flip to check your answerFold answer back

Perfect answer: Django calls the view with a request object, plus any values captured from the path. The view makes a decision and either returns a response object or raises an exception that Django handles, such as Http404. It does not print to the browser, and it does not return bare text: printing goes to the server’s terminal, and only the returned response travels back to the browser.

Table 10.4 — Printing compared with returning a response
Question print('Hello') return HttpResponse('Hello')
Where does it go? The server's terminal Back to the browser
Has a status? No Yes
Has headers? No Yes, including Content-Type
Ends the view? No Yes

Behind the scenes:

# BaseHandler._get_response(request):
#     match = resolver.resolve(request.path_info)
#     response = view(request, *args, **kwargs)
#     if response is None: raise ValueError(...)

Code proof: call the view directly with a built request:

uv run python manage.py shell -c "
from django.test import RequestFactory
from events.views import event_detail
request = RequestFactory().get('/events/1/')
response = event_detail(request, 1)
print(response.status_code, response['Content-Type'])
print(response.content)
"
12 objects imported automatically (use -v 2 for details).

200 text/plain
b'Sample: Python meetup'

Common mistakes:

  • Confusing server terminal output with an HTTP response.
  • Returning a bare string.
  • Assuming every view returns HTML; ours returns plain text.

Follow-up the interviewer might ask:

  • “What happens if a view forgets to return anything?”
  • “Why is a view easy to test without a server?”

L2 (Mid-Level): How does the event ID reach the view?

What the interviewer is testing: Can you follow a captured URL value into Python?

Flip to check your answerFold answer back
A request for events slash 1 reaches an integer path converter, which passes integer 1 as event_id to the detail view.
Figure 10.2 — The route supplies an integer to the view.

Perfect answer: The route events/<int:event_id>/ has a named integer converter. It matches digits in that part of the path and converts them, and Django passes the value to the view as the keyword argument event_id. So the name in the route must match the view’s parameter, and the view receives an integer rather than text. The converter checks only the shape of the value: 999 passes it, even though no such sample exists, and abc fails it, so that path matches no route.

Behind the scenes:

# class IntConverter:
#     regex = '[0-9]+'
#     def to_python(self, value): return int(value)

Code proof: resolve a path and read what the view will receive:

uv run python manage.py shell -c "
from django.urls import resolve
match = resolve('/events/1/')
print(match.func.__name__, match.kwargs)
print(type(match.kwargs['event_id']).__name__)
"
12 objects imported automatically (use -v 2 for details).

event_detail {'event_id': 1}
int

Common mistakes:

  • Assuming the converter finds a stored record.
  • Using a different parameter name in the view.
  • Treating the integer as trusted because it was converted; it still came from the request.

Follow-up the interviewer might ask:

  • “What happens to letters in place of the ID?”
  • “What would you use for an address built from an event’s short name?”

L3 (Senior): Why can two different problems both return 404?

What the interviewer is testing: Can you distinguish URL resolution from a missing resource?

Flip to check your answerFold answer back
A non-integer event path fails route matching. A numeric path reaches the view, where an absent sample raises Http404. Both outcomes return status 404.
Figure 10.3 — Two paths to a 404 response.

Perfect answer: A path can fail to match any route, so Django raises Resolver404 and no view runs. Or a path can match a route whose view then raises Http404, because the resource it was asked for is missing. A visitor sees the same status in both cases, and that is the right answer for both, but the causes live in different places. So a developer asks whether a view ran. Returning a 200 page containing the words “not found” would be worse than either, because browsers, search engines, and tests would all take it for success.

Behind the scenes:

# class Resolver404(Http404): raised when no route matches.
# Because it is a kind of Http404, the handler turns
# both into the same 404 response.

Code proof: the two addresses from this chapter, one for each cause:

uv run python manage.py shell -c "
from django.http import Http404
from django.test import RequestFactory
from django.urls import Resolver404, resolve
try:
    resolve('/events/abc/')
except Resolver404:
    print('abc: no route matched')
match = resolve('/events/999/')
try:
    match.func(RequestFactory().get('/'), **match.kwargs)
except Http404 as error:
    print('999:', match.view_name, 'raised', error)
"
12 objects imported automatically (use -v 2 for details).

abc: no route matched
999: events:detail raised Sample event not found

Common mistakes:

  • Concluding that every 404 means the route is missing.
  • Returning a 200 response containing the words “not found”.
  • Testing a 404 without checking which view, if any, was selected.

Follow-up the interviewer might ask:

  • “How does test_missing_event show that its 404 came from the view?”
  • “Should a visitor be told which cause applied?”

L4 (Staff): How would you prevent unsafe HTML output?

What the interviewer is testing: Can you separate this controlled example from untrusted data in a real application?

Flip to check your answerFold answer back
Identify the source of data, select the output context, apply suitable escaping, and test the rendered result.
Figure 10.4 — Choose protections for the output context.

Perfect answer: First identify which values come from untrusted sources, and where each is written. HttpResponse writes exactly what it is given and labels it HTML by default, so joining untrusted text into a response is how pages get hijacked. For HTML, I would render through Django templates, which escape ordinary values, and avoid marking untrusted content as safe. Validation is separate: it decides what a value may be, not how it is written out, and no single control covers every output context. Finally I would test hostile-looking input. Our sample avoids the problem only because its title is fixed and it is sent as plain text. Chapter 11 takes up templates.

Behind the scenes:

# escape(text): replace & < > " and ' with HTML entities,
#     so a browser shows those characters as text.
# HttpResponse(content) applies no escaping at all.

Code proof: the same harmless title, written out directly and then escaped:

uv run python manage.py shell -c "
from django.http import HttpResponse
from django.utils.html import escape
title = '<b>Sample</b>'
print(HttpResponse(title).content)
print(escape(title))
"
12 objects imported automatically (use -v 2 for details).

b'<b>Sample</b>'
&lt;b&gt;Sample&lt;/b&gt;

Common mistakes:

  • Assuming that a plain-text example proves arbitrary HTML is safe.
  • Treating validation as a replacement for escaping suited to the output.
  • Building HTML by joining strings in a view.

Follow-up the interviewer might ask:

  • “Where will Otahque render HTML?”
  • “Which values would you treat as untrusted once members can edit events?”

L5 (Lead): What does this checkpoint actually prove?

What the interviewer is testing: Can you state evidence and its limits without overstating readiness?

Flip to check your answerFold answer back
Define the expected behaviour, run tests and local checks, record the observed results, and name the remaining gaps.
Figure 10.5 — Connect an observed check to its limits.

Perfect answer: It proves that these local routes and this fixed sample behave as stated, under the tested conditions, on the platforms we ran. It says nothing about stored events, access rules, production deployment, accessibility, or other browsers, and a report that claimed those would mislead whoever plans the next step. So I would report the check, the result, and the gaps together, and name who decides whether the gaps matter yet. Listing what the tests actually cover is often the quickest way to show the boundary.

Behind the scenes:

# The runner collects test methods and reports each result.
# It knows nothing about behaviour that no test asserts:
# anything unasserted is simply absent from the report.

Code proof: list every test the project has, which is also the list of what it claims:

uv run python manage.py shell -c "
import unittest
tests = unittest.defaultTestLoader.loadTestsFromName(
    'events.tests'
)
for group in tests:
    for test in group:
        print(test.id().removeprefix('events.tests.'))
"
12 objects imported automatically (use -v 2 for details).

EventDetailTests.test_invalid_id
EventDetailTests.test_missing_event
EventDetailTests.test_sample_event
RoutingTests.test_event_list
RoutingTests.test_home
RoutingTests.test_unknown_path

Nothing here mentions a database, a permission, or a browser, and that absence is part of the evidence.

Common mistakes:

  • Calling a sample dictionary a database.
  • Treating a passing test as proof of the whole product.
  • Reporting a pass without saying what was not checked.

Follow-up the interviewer might ask:

  • “What would you check next, and why that first?”
  • “Who should decide that a known gap is acceptable?”

Next: Chapter 11 introduces templates, context, and escaping.

PAGE 006