Thuta Learning
Python
IntermediateProgrammingBeginner

Django Views & Templates

PythonLesson 3935 min

What you'll walk away with

  • Map a URL to a view with path() and receive values through converters such as <int:pk>
  • Return an HttpResponse from render() by giving a template a context dict
  • Use {{ }}, {% %}, filters and {% extends %} / {% block %} template inheritance
  • Explain why autoescaping blocks XSS and when |safe must not be used
  • Raise Http404 for a missing record and check status codes with the test Client

Explain it simply

Views and templates in plain language

In Django, a view is a Python function (or class) that receives a request and returns a response. A template is an HTML file with blanks in it, and the view fills those blanks with data. The view decides what to show; the template decides how it looks.

Think of a restaurant. The URL is the dish name on the menu, the view is the cook in the kitchen, and the template is the plate the food is served on. A cook does not make plates by hand, and a view should not glue HTML strings together by hand either.

Problem → Why → Solution

The problem: building HTML with strings inside the view

You want a blog post page fast, so the view writes HTML directly with an f-string. It works for the first two posts, but the day a user puts a <script> tag in a title, that script runs in the browser of everyone who opens the page. The same view crashes with a KeyError and a 500 error for an id that does not exist, and every layout change means editing Python code.

views.py
from django.http import HttpResponse

def post_detail(request, pk):
    post = POSTS[pk]  # KeyError -> 500 for an unknown id
    # user text goes into the page unescaped: an XSS hole
    return HttpResponse(f"<h1>{post['title']}</h1><p>{post['body']}</p>")

Why templates and Http404 are the fix

The Django template engine escapes every value inside {{ }} by default, so characters like < and > show up as text instead of becoming tags. Raising Http404 makes Django send a correct 404 response instead of a 500 crash. And because the layout lives in a template file, a designer can change it without touching Python.

Core concept: URL → view → template → response

When a request arrives, Django walks the urlpatterns list in urls.py from top to bottom and picks the first path() that matches. In path("posts/<int:pk>/", post_detail), <int:pk> is a converter: that part of the URL only matches digits, is converted to an int, and is passed to the view as the keyword argument pk. A URL like /posts/abc/ matches no pattern, so it becomes a 404 before any view runs.

The view's job is to read the request, look up the data and choose a response. render(request, "post_detail.html", context) finds the template, fills it with the values in the context dict and returns an HttpResponse object. If a view forgets to return a response, Django raises a ValueError saying the view didn't return an HttpResponse object. When the data is missing, raise Http404; with a model, the get_object_or_404(Post, pk=pk) shortcut does it in one line.

Template syntaxWhat it does
{{ post.title }}prints a value, escaped (dict key, attribute and index all use the dot)
{% for %} ... {% empty %}loops, and shows the {% empty %} part for an empty list
{{ tags|join:', ' }}a filter: changes how a value is displayed
{% extends %} / {% block %}inherits a base layout and replaces only its blocks

The template language is limited on purpose: you cannot call a function with arguments, and new database queries do not belong in a template. Logic stays in the view, and the template only displays data that is already prepared. A variable that is missing from the context does not raise an error; it simply renders as an empty string, so typos are only caught by tests.

The journey of one request
  1. URLconf matches the path
  2. Converter turns pk into an int
  3. View finds data, builds context
  4. Template fills it in, escaped
  5. HttpResponse goes back (200/404)

Each step fails differently: no matching pattern gives a 404, a crashing view gives a 500, and a missing variable gives blank text.

General pattern

python
# urls.py
urlpatterns = [path("items/<int:pk>/", item_detail, name="item-detail")]

# views.py
def item_detail(request, pk):
    item = find_item(pk)          # or get_object_or_404(Model, pk=pk)
    if item is None:
        raise Http404("not found")
    return render(request, "app/item_detail.html", {"item": item})

A URL pattern, a view function, a template name and a context dict: most Django pages follow this shape. Giving the pattern a name= lets templates rebuild the URL with {% url 'item-detail' pk %} instead of hard-coding it.

Worked example: a blog list and detail page

So that this example runs as one file, it sets Django up inside the script with settings.configure(). That is only for the demo: in a real project these settings live in settings.py and the templates are .html files in a templates/ folder. The locmem loader keeps the templates in a dict.

Notice that one of the two post titles contains an HTML tag. At the end, the test Client requests three URLs and prints each status code and the rendered HTML.

views_templates_demo.py
import django
from django.conf import settings

# Single-file demo only: in a real project these live in settings.py
# and templates/*.html. The locmem loader keeps the templates in a dict.
TEMPLATE_SOURCES = {
    "base.html": (
        "<h1>{% block title %}My Blog{% endblock %}</h1>\n"
        "{% block content %}{% endblock %}"
    ),
    "post_list.html": (
        "{% extends 'base.html' %}{% block content %}"
        "{% for pk, post in posts.items %}"
        "<a href=\"{% url 'post-detail' pk %}\">{{ post.title }}</a>\n"
        "{% empty %}No posts yet.{% endfor %}{% endblock %}"
    ),
    "post_detail.html": (
        "{% extends 'base.html' %}{% block title %}{{ post.title }}{% endblock %}"
        "{% block content %}Tags: {{ post.tags|join:', '|default:'none' }}"
        "{% endblock %}"
    ),
}
settings.configure(
    ALLOWED_HOSTS=["testserver"],
    ROOT_URLCONF=__name__,
    TEMPLATES=[{
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "OPTIONS": {"loaders": [
            ("django.template.loaders.locmem.Loader", TEMPLATE_SOURCES),
        ]},
    }],
)
django.setup()

from django.http import Http404
from django.shortcuts import render
from django.test import Client
from django.urls import path

POSTS = {
    1: {"title": "Hello Django", "tags": ["intro", "web"]},
    2: {"title": "<b>Bold</b> claims", "tags": []},
}


def post_list(request):
    return render(request, "post_list.html", {"posts": POSTS})


def post_detail(request, pk):
    post = POSTS.get(pk)
    if post is None:
        raise Http404("No post with that id")
    return render(request, "post_detail.html", {"post": post})


urlpatterns = [
    path("", post_list, name="post-list"),
    path("posts/<int:pk>/", post_detail, name="post-detail"),
]

client = Client()
for url in ["/", "/posts/2/", "/posts/99/"]:
    response = client.get(url)
    print(f"GET {url} -> {response.status_code}")
    if response.status_code == 200:
        print(response.content.decode().strip())

Code breakdown

  1. Base layout with blocks"<h1>{% block title %}My Blog{% endblock %}</h1>\n"

    base.html is the layout every page shares. Each {% block %} is a slot a child template may replace, and the text inside it is the default.

  2. Loop with a URL tag"<a href=\"{% url 'post-detail' pk %}\">{{ post.title }}</a>\n"

    {% url %} rebuilds /posts/1/ from the pattern named post-detail. {{ post.title }} is escaped, so the <b> tag appears in the output as entity codes, not as bold text.

  3. Settings for a single fileROOT_URLCONF=__name__,

    Tells Django to look for urlpatterns in this very script. In a real project it is a setting such as ROOT_URLCONF = "mysite.urls".

  4. 404 instead of a crash raise Http404("No post with that id")

    When POSTS.get(pk) returns None, the view raises Http404. Django catches it and turns it into a 404 response, so /posts/99/ gives 404 rather than 500.

  5. URL converter path("posts/<int:pk>/", post_detail, name="post-detail"),

    <int:pk> turns the digits in the URL into an int and calls post_detail(request, pk=2), which is why the int keys of POSTS can be looked up directly.

  6. Test Client response = client.get(url)

    The Client pushes a full request through URL routing, the view and the template without starting a server. Django also logs a 'Not Found' line to stderr for the 404.

You should see
GET / -> 200
<h1>My Blog</h1>
<a href="/posts/1/">Hello Django</a>
<a href="/posts/2/">&lt;b&gt;Bold&lt;/b&gt; claims</a>
GET /posts/2/ -> 200
<h1>&lt;b&gt;Bold&lt;/b&gt; claims</h1>
Tags: none
GET /posts/99/ -> 404
Execution flow of GET /posts/2/
  1. URLconf matches posts/<int:pk>/ with pk=2
  2. post_detail(request, pk=2) is called
  3. POSTS.get(2) finds the post
  4. render() fills post_detail.html, which extends base.html
  5. A 200 response with escaped HTML

Post exists

200 + rendered HTML

Post missing

raise Http404 -> 404

From one file to a real project

In a real project the pieces above are split across three files. Views query a model, URLs are declared in the app's urls.py, and templates sit in an app/templates/<app>/ folder. Repeating the app name in the template path stops two apps' detail.html files from colliding.

blog/views.py
from django.shortcuts import get_object_or_404, render

from .models import Post


def post_list(request):
    posts = Post.objects.order_by("-created_at")[:20]
    return render(request, "blog/post_list.html", {"posts": posts})


def post_detail(request, pk):
    post = get_object_or_404(Post, pk=pk)
    return render(request, "blog/post_detail.html", {"post": post})
blog/templates/blog/post_list.html
{% extends "base.html" %}
{% load static %}

{% block content %}
  <link rel="stylesheet" href="{% static 'blog/style.css' %}">
  <ul>
    {% for post in posts %}
      <li><a href="{% url 'post-detail' post.pk %}">{{ post.title }}</a></li>
    {% empty %}
      <li>No posts yet.</li>
    {% endfor %}
  </ul>
{% endblock %}

{% load static %} and the {% static %} tag build URLs for CSS, JavaScript and image files from the STATIC_URL setting. Class-based views such as ListView and DetailView finish this list/detail pattern with less code, but they do the same work underneath, so it pays to understand function views first.

In real projects

Views and templates in real projects

Most pages of a typical content site are list pages and detail pages: a blog post list and a single post, a product catalog and a product page, an order history and one order. Every one of those pages raises the same questions: does a missing record return 404, is this user allowed to see it, and how many queries does it run?

  • Pagination: list views use Paginator or ListView's paginate_by instead of putting thousands of rows on one page.
  • Query count: reading a relation like {{ post.author.name }} inside a template loop can run one extra query per row; fetch it up front in the view with select_related().
  • Base template: the header, navigation and footer are written once in base.html and every page uses {% extends %}, so a redesign touches one file.
  • Tests: Client tests that check 200, 404 and permission redirects reveal breakage immediately when URLs or templates are refactored.

Common mistakes

Common mistakes with views and templates

Marking user text with |safe or mark_safe

|safe tells Django 'I trust this HTML' and switches escaping off. Showing comments, titles or profile bios that users typed with |safe is a direct XSS hole. If you need rich text, run it through a sanitizer that keeps only an allowlist of tags.

Returning 200 or 500 for a missing object

Using POSTS[pk] or Post.objects.get(pk=pk) directly raises an exception for every bad id and produces a 500. Returning a 'not found' message with status 200 misleads search engines and monitoring too. Use get_object_or_404 or raise Http404.

Putting logic and queries in the template

Writing {{ post.comments.count }} inside a loop runs one query per row and slows the page down. Business rules such as price calculations or permission checks are also hard to test when they live in a template. Prepare the data in the view with annotate() or prefetch_related() and keep the template simple.

Mini challenge

Mini challenge: a product list with search

Write a view that reads ?q= from the query string and filters a list of products. Show the results with a template, with an {% empty %} message when nothing matches. This time build requests with RequestFactory instead of Client and call the view function directly.

  • Read the search text with request.GET.get("q", "") and match case-insensitively
  • Reject searches longer than 30 characters with HttpResponseBadRequest (400)
  • The template shows the result count and formats prices with floatformat:2
  • Try four requests: a match, no match, a too-long query, and no q at all
product_search.py
import django
from django.conf import settings

settings.configure(TEMPLATES=[{
    "BACKEND": "django.template.backends.django.DjangoTemplates",
    "OPTIONS": {"loaders": [("django.template.loaders.locmem.Loader", {
        # TODO: "products.html": show the query, the count, each name and
        # price (floatformat:2), and an {% empty %} message
    })]},
}])
django.setup()

from django.test import RequestFactory

PRODUCTS = [
    {"name": "Mechanical keyboard", "price": 49},
    {"name": "Wireless mouse", "price": 19.5},
    {"name": "USB-C hub", "price": 25},
]


def product_list(request):
    # TODO: read q, reject long input with a 400, filter, render the template
    ...


factory = RequestFactory()
# TODO: call product_list with four different query strings and print the results

Expected: 'mouse' shows Wireless mouse (19.50), 'laptop' shows 'Nothing matched.', a 40-character query returns 400, and no q lists all three products.

Show hint

factory.get("/products/", {"q": "mouse"}) returns a request whose request.GET contains q. RequestFactory skips middleware and URL routing, so you call the view like an ordinary function.

Show solution
product_search.py
import django
from django.conf import settings

settings.configure(TEMPLATES=[{
    "BACKEND": "django.template.backends.django.DjangoTemplates",
    "OPTIONS": {"loaders": [("django.template.loaders.locmem.Loader", {
        "products.html": (
            "Results for '{{ query }}': {{ products|length }}\n"
            "{% for p in products %}- {{ p.name }} ({{ p.price|floatformat:2 }})\n"
            "{% empty %}Nothing matched.\n{% endfor %}"
        ),
    })]},
}])
django.setup()

from django.http import HttpResponseBadRequest
from django.shortcuts import render
from django.test import RequestFactory

PRODUCTS = [
    {"name": "Mechanical keyboard", "price": 49},
    {"name": "Wireless mouse", "price": 19.5},
    {"name": "USB-C hub", "price": 25},
]


def product_list(request):
    query = request.GET.get("q", "").strip()
    if len(query) > 30:
        return HttpResponseBadRequest("Search text is too long")
    matches = [p for p in PRODUCTS if query.lower() in p["name"].lower()]
    return render(request, "products.html", {"query": query, "products": matches})


factory = RequestFactory()
for params in [{"q": "mouse"}, {"q": "laptop"}, {"q": "x" * 40}, {}]:
    response = product_list(factory.get("/products/", params))
    print(response.status_code, response.content.decode().strip())
    print("---")

Quick quiz 1 / 3

The context is {"name": "<i>Mya</i>"} and the template is <p>{{ name }}</p>. What does the browser show?

Quick quiz 2 / 3

urlpatterns contains only path("posts/<int:pk>/", post_detail). What happens on GET /posts/abc/?

Quick quiz 3 / 3

post is in the context but has no subtitle key. What does {{ post.subtitle }} produce?

What to remember

  • The URLconf checks path() patterns in order, and converters like <int:pk> hand values to the view.
  • A view finds the data and must return an HttpResponse, usually from render(request, template, context).
  • Templates escape every value inside {{ }}; never use |safe on user data.
  • {% extends %} and {% block %} keep the layout in one place.
  • Use Http404 or get_object_or_404 for missing records, and test status codes with the Client.

Django — Getting Started — Django Software Foundation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Django Views & Templates | Thuta Learning