Skip to lesson content

PROJECT 2 · LESSON 3 OF 16

Build a reusable business website

Separate HTML from Python and reuse a base template across pages.

  • templates
  • context
  • inheritance
  • static assets

Your workspace: edushop

Continue from lesson 2: Add routes and understand requests. Keep existing files; create or replace the complete files listed below.

Extract the ZIP and open the folder containing manage.py. Create a Python virtual environment, install requirements.txt and run migrate. Read README.md for checkpoint-specific commands and LESSON.md for offline explanations. Checkpoints contain no database records or private credentials.

1. Understand the problem and the concepts

Why we need this feature

Repeating an entire HTML document for every page makes changes expensive. A business website is a useful first refactoring project: several pages need different content but the same navigation, document structure and visual style.

Continue the same project. Templates are rendered on the server: the browser receives HTML, not Python or executable Django template tags.

A context dictionary gives the template its values. Template inheritance replaces repeated page structure with a base document and named blocks.

A view prepares data; a template presents it

render(request, template_name, context) loads a template, combines it with a dictionary of values and returns an HTML response. The view decides what data is available. The template decides how it appears. This is Django’s model-template-view vocabulary: a Django view performs request handling, while a template performs much of the presentation responsibility.

Template expressions are deliberately smaller than Python. Use {{ value }} for output and {% ... %} for tags such as loops, conditions and URL generation. Keep database writes and business calculations out of templates. When the catalog grows, its view will query products and its template will loop over the result.

Inheritance and includes are different forms of reuse

base.html supplies the surrounding document and named blocks. A child template extends it and replaces the content block, so navigation stays consistent across pages. Think of a block as a named slot, not a second complete document. Put extends first in the child template.

An include renders a smaller fragment inside the current page. We will use it for product cards later. Inheritance defines the page skeleton; includes reuse smaller sections. Neither requires client-side state. Every normal page request renders a fresh HTML response on the server.

Static files are separate requests

A CSS file is not embedded into the rendered template automatically. The static template tag generates its URL, and the browser requests that URL after reading the HTML. The shop/static/shop namespace avoids collisions with other apps that may also have a site.css. STATIC_URL is a URL prefix; STATIC_ROOT will be a collected output directory for deployment.

During development, Django serves static assets when configured appropriately with DEBUG enabled. Production serves collected files through WhiteNoise in this course. Never fix a production missing-CSS problem by enabling DEBUG. First establish which CSS URL the page requested and whether the collected file exists.

Templates escape ordinary variable output. If you later display a product description containing <script>, it should appear as text. The safe filter bypasses that protection and should not be used on arbitrary user input.

2. Follow the execution flow

Read this sequence before the source. Identify the input, the component or function that handles it, and the result the learner sees.

  1. A page URL selects its view.

  2. The view calls render with a named template and a context dictionary.

  3. The template extends base.html and supplies its content block.

  4. URL and static tags resolve application addresses and asset addresses.

  5. The browser renders HTML and makes a separate request for the CSS.

Change the site navigation once

  1. Open home and about in separate tabs.
  2. Change the navigation text in base.html.
  3. Refresh both pages. Both use the new navigation because they share the same parent template.

3. Build it, one file at a time

  1. Replace the views and add the templates and stylesheet below.
  2. Notice that the home page loops over a list from Python and includes one reusable feature partial.
  3. Change the navigation in base.html and confirm that both Home and About use it.

The paths below are relative to your practice project. Each block is the complete file at this checkpoint. Read its responsibility first, type or copy the code, then use the walkthrough to explain the important statements.

shop/views.py

Prepare data and ask Django to render a template.

shop/views.py
from django.http import HttpResponse
from django.shortcuts import render


def home(request):
    return render(request, "shop/home.html", {"features": ["Learn", "Build", "Share"]})


def about(request):
    return render(request, "shop/about.html")


def greeting(request, name):
    return HttpResponse(f"Hello, {name}!", content_type="text/plain")

Read the code

  1. render combines request, template path and an optional context dictionary into HttpResponse.
  2. Business data stays in Python; the template decides how to present it.

templates/base.html

Provide the shared HTML document, navigation and content slots.

templates/base.html
{% load static %}
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>{% block title %}EduShop{% endblock %}</title>
  <link rel="stylesheet" href="{% static 'shop/site.css' %}">
</head>
<body>
<nav aria-label="Main navigation">
  <a href="{% url 'shop:home' %}">Home</a>
  <a href="{% url 'shop:about' %}">About</a>
</nav>
{% for message in messages %}<p role="status">{{ message }}</p>{% endfor %}
<main>{% block content %}{% endblock %}</main>
<footer>EduShop · Built while learning Django</footer>
</body>
</html>

Read the code

  1. extends in a child template reuses this document; block content is where that child supplies its page.
  2. url resolves named routes and static builds the asset URL. These are server-side template tags, not browser JavaScript.
  3. Messages report the outcome after a redirect. Once authentication is added, logout uses a CSRF-protected POST form.

templates/shop/home.html

Provide the home page’s content within the shared layout.

templates/shop/home.html
{% extends "base.html" %}
{% block title %}Welcome to EduShop{% endblock %}
{% block content %}
<h1>Build your learning workspace</h1>
<p>A small business website, growing into an online store.</p>
<div class="grid">{% for feature in features %}{% include "shop/_feature.html" with title=feature %}{% endfor %}</div>
{% endblock %}

Read the code

  1. extends selects the base; block content replaces only that named area.
  2. The loop reads features from the context. include passes the current value as title to the partial.

templates/shop/_feature.html

Own the repeated feature-card markup.

templates/shop/_feature.html
<article><h2>{{ title }}</h2><p>Make progress through practical projects.</p></article>

Read the code

  1. Double braces output a context value with HTML escaping by default.
  2. A leading underscore is only our naming convention for partials; it has no special Django runtime behavior.

templates/shop/about.html

Render a second page using the same document.

templates/shop/about.html
{% extends "base.html" %}
{% block title %}About EduShop{% endblock %}
{% block content %}<h1>About EduShop</h1><p>We help learners create a useful workspace.</p>{% endblock %}

Read the code

  1. Only its title and content blocks change. Navigation remains owned by the base template.

shop/static/shop/site.css

Style all pages through one namespaced static asset.

shop/static/shop/site.css
* { box-sizing: border-box; }
body { max-width: 1000px; margin: auto; padding: 24px; font: 17px/1.7 system-ui; color: #17352a; }
nav { display: flex; flex-wrap: wrap; align-items: center; gap: 18px; border-bottom: 1px solid #cbd9d3; padding-bottom: 18px; }
nav form { margin: 0; padding: 0; border: 0; }
a { color: #176746; }
main { min-height: 65vh; padding: 24px 0; }
article, form { border: 1px solid #cbd9d3; border-radius: 10px; padding: 20px; margin: 16px 0; }
.grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 16px; }
input, textarea, select, button { font: inherit; max-width: 100%; padding: 8px; }
label { display: block; }
button { cursor: pointer; }
.errorlist { color: #a41425; }
:focus-visible { outline: 3px solid #b36b00; outline-offset: 3px; }

Read the code

  1. shop/static/shop prevents ambiguous names when multiple apps have CSS. The static tag resolves shop/site.css.
  2. runserver serves development assets; production asset collection is taught in Project 8.

4. Run it and check your result

  • Both pages have the same header and styling.
  • Three feature cards appear from a single included template.

5. Predict, change and observe

Rename the CSS file without changing the static tag. Predict which parts fail.

Compare your prediction with the expected result

What you should observe

The page content still appears, but styling is missing and the CSS request returns 404.

Why it happens

Template rendering and asset delivery are separate operations. A valid HTML response does not prove that every referenced asset exists.

6. Troubleshoot with evidence

A common mistake

Do not use the safe filter to silence escaping. Ordinary customer-supplied text should remain escaped.

TemplateDoesNotExist

Likely cause: The file path does not match the configured template search locations.

Check and correct: Check templates/base.html and shop/templates/shop/... plus DIRS and APP_DIRS.

NoReverseMatch

Likely cause: A URL tag uses the wrong namespace, route name or arguments.

Check and correct: Compare the tag with app_name and the path name in shop/urls.py.

7. Practice and explain it back

Your independent task

Add a Delivery page extending base.html.

Attempt these questions before opening the explanations. Use the source above to justify your answer.

Why not repeat navigation in each page?

Copies drift apart. Inheritance puts shared markup in one file and makes each page express only its differences.

Why is CSS namespaced with shop twice in the filesystem?

The first shop is the Python app. static is the discovery directory, and the inner shop becomes the public namespace that distinguishes this app’s assets.