Django views, URLs and templates
Django follows a pattern called MTV: Models hold the data, Templates describe how pages look, and Views connect them, handling each request. URLs decide which view runs. This lesson builds pages and JSON endpoints with all four.
Request → URL → view → response
GET /products/3/ → urls.py: path("products/<int:pk>/", views.product_detail)
→ views.product_detail(request, pk=3)
→ HttpResponse (HTML from a template, or JSON)A view is a function that takes a request and returns a response:
On your computer,
python manage.py runserverserves these athttp://127.0.0.1:8000/. In the editors, Django's testClientsends the requests instead, which is also how you write Django tests.
URL patterns
| Pattern | Matches | Passes |
|---|---|---|
path("products/", …) |
/products/ |
nothing |
path("products/<int:pk>/", …) |
/products/42/ |
pk=42 (an int) |
path("blog/<slug:slug>/", …) |
/blog/hello-world/ |
slug="hello-world" |
path("files/<path:p>", …) |
/files/a/b/c.txt |
p="a/b/c.txt" |
include("shop.urls") |
Everything under a prefix | delegates to the app's own urls.py |
Give every route a name, and build links with reverse("name") in Python or {% url 'name' %} in templates, so changing a URL never breaks links.
Templates
Templates are HTML files with variables {{ … }}, tags {% … %} and filters |. Django escapes variables automatically, so user content can't inject HTML or scripts.
Notice:
- Template inheritance: pages
{% extends "base.html" %}and fill its{% block %}s, so the layout lives in one place. - The product named
<script>…was escaped to<script>: no XSS. get_object_or_404turned a missing product into a 404 page.
| Template feature | Example |
|---|---|
| Variables and attributes | {{ product.name }}, {{ order.items.count }} |
| Filters | upper, lower, date:"j M Y", default:"–", truncatewords:10, floatformat:2, pluralize |
| Conditions | {% if %} {% elif %} {% else %} {% endif %} |
| Loops | {% for x in list %} … {% empty %} … {% endfor %}, plus forloop.counter |
| Links | {% url 'route_name' arg %} |
| Reuse | {% extends %}, {% block %}, {% include "partial.html" %} |
| Forms | {% csrf_token %} inside every POST form |
Handling POST requests
Django requires a CSRF token on POST requests from browsers (the CsrfViewMiddleware). In templates, add {% csrf_token %} inside each <form method="post">. JSON APIs typically use Django REST framework (later lesson), which handles authentication and CSRF differently.
Practice
- Add a
products/<int:pk>/buy/view that reduces the stock by one and redirects (redirect("product_detail", pk=pk)) back to the product. - Show "1 item" / "2 items" in the list title using the
pluralizefilter. - Add a search box:
products/?q=lampfilters the list withname__icontains.
1.What does <int:pk> in a URL pattern do?
2.Why does {{ product.name }} with <script> in it not run as JavaScript?
3.What must every POST form in a Django template contain?