Skip to lesson content

PROJECT 3 · LESSON 6 OF 16

Build product pages, search and pagination

Read database records into reusable templates and handle missing products.

  • QuerySets
  • get_object_or_404
  • slug routes
  • pagination

Your workspace: edushop

Continue from lesson 5: Create a database-backed product catalog. 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

A database catalog becomes useful when visitors can browse, search and open one product. This project connects stored records to reusable templates while keeping lookup failures and large result sets predictable.

The public catalog displays active products only. The admin may contain archived records that customers should no longer see.

QuerySets describe database queries and are evaluated when results are needed. Filtering in the database avoids loading the entire catalog just to search it in Python.

Build a QuerySet before evaluating it

Product.objects.filter(active=True) describes a query for visible products. Additional filters narrow it. QuerySets are generally lazy: constructing one does not immediately retrieve every row. Iteration, pagination and other evaluation operations cause database work. Put filtering in the database instead of loading all rows into Python and discarding most of them.

The q query parameter is optional search input. Trim it and apply name__icontains when it is non-empty. The ORM passes values as query parameters rather than asking you to concatenate SQL. Parameterization protects SQL structure; it does not replace limits, authorization or decisions about which fields visitors may search.

Lists and details have different contracts

A list may legitimately be empty, so render an empty-state message. A detail request promises one identifiable object, so use get_object_or_404 with slug and active=True. An inactive product should not remain publicly accessible merely because someone memorized its address. The filter belongs in both paths.

A detail URL generated with the product slug is easier to read than a copied literal string. The URL tag uses the route name and arguments; if the route changes, link generation remains centralized. The card include receives a product and renders the same structure wherever used.

Pagination changes the query, not only the appearance

Paginator limits how many products appear on one page. Preserve q when generating page links so page two continues the same search. Use urlencode when putting user input into a query string; spaces and ampersands otherwise change the meaning of the URL.

An ordering such as name then primary key gives stable results when two products share a name. Without a consistent ordering, records can appear to move between pages. Pagination is also a usability decision: keep search text visible and show an understandable empty result rather than a blank screen.

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. GET /products/?q=note&page=1 reaches the catalog view.

  2. The view filters active products and applies optional search.

  3. Paginator selects the requested slice.

  4. The template loops over that slice and includes a card for each product.

  5. A detail link sends a new request, which looks up one active slug or returns 404.

Search and visibility together

  1. Search for part of a seeded product name.
  2. Deactivate that product in admin and repeat the search.
  3. Open its old detail address. Both the list and detail now respect active=False.

3. Build it, one file at a time

  1. Add the catalog views and routes. Create the card, catalog and details templates.
  2. Seed the products and open /products/. Click a card, then try an unknown slug.
  3. Create more than six products through admin and navigate between pages. Search for pen and check the URL.

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

Add collection and detail reads to the existing business-site views.

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")

from django.contrib import messages
from django.shortcuts import redirect
from .forms import ContactForm


def contact(request):
    form = ContactForm(request.POST if request.method == "POST" else None)
    if request.method == "POST" and form.is_valid():
        # Learning preview only: no email or storage is performed at this stage.
        messages.success(request, "Your enquiry passed validation. This practice form does not send email yet.")
        return redirect("shop:contact")
    return render(request, "shop/contact.html", {"form": form})

from django.core.paginator import Paginator
from django.shortcuts import get_object_or_404
from .models import Product


def products(request):
    q = request.GET.get("q", "").strip()[:100]
    rows = Product.objects.filter(active=True)
    if q:
        rows = rows.filter(name__icontains=q)
    page = Paginator(rows, 6).get_page(request.GET.get("page"))
    return render(request, "shop/products.html", {"page": page, "q": q})


def product_detail(request, slug):
    product = get_object_or_404(Product, slug=slug, active=True)
    return render(request, "shop/product_detail.html", {"product": product})

Read the code

  1. filter(active=True) applies visibility before searching. name__icontains adds case-insensitive matching.
  2. Paginator selects six records per page. get_page tolerates malformed page input with a usable page.
  3. get_object_or_404 combines lookup and missing-record handling, so an inactive or unknown slug does not crash the template.

shop/urls.py

Expose collection and slug-based product routes.

shop/urls.py
from django.urls import path
from . import views

app_name = "shop"
urlpatterns = [
    path("", views.home, name="home"),
    path("about/", views.about, name="about"),
    path("hello/<str:name>/", views.greeting, name="greeting"),
    path("products/", views.products, name="products"),
    path("products/<slug:slug>/", views.product_detail, name="product-detail"),
    path("contact/", views.contact, name="contact"),
]

Read the code

  1. The slug converter accepts a URL-friendly product identifier and passes slug to the view.
  2. Route names allow product cards to reverse the details URL using the actual slug.

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>
  <a href="{% url 'shop:contact' %}">Contact</a>
  <a href="{% url 'shop:products' %}">Products</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/_product.html

Render one catalog item with a named details link.

templates/shop/_product.html
<article><h2><a href="{% url 'shop:product-detail' product.slug %}">{{ product.name }}</a></h2><p>{{ product.description }}</p><strong>₹{{ product.price }}</strong></article>

Read the code

  1. The same partial can be included on a search page or a category page without duplicating markup.
  2. Template values are escaped by default. Avoid using raw HTML for product descriptions in this beginner store.

templates/shop/products.html

Keep search and paging state in shareable GET parameters.

templates/shop/products.html
{% extends "base.html" %}
{% block content %}<h1>Products</h1>
<form method="get"><label>Search <input name="q" value="{{ q }}" maxlength="100"></label><button>Search</button></form>
<div class="grid">{% for product in page %}{% include "shop/_product.html" %}{% empty %}<p>No products match.</p>{% endfor %}</div>
<nav aria-label="Product pages">{% if page.has_previous %}<a href="?q={{ q|urlencode }}&page={{ page.previous_page_number }}">Previous</a>{% endif %}<span>Page {{ page.number }} of {{ page.paginator.num_pages }}</span>{% if page.has_next %}<a href="?q={{ q|urlencode }}&page={{ page.next_page_number }}">Next</a>{% endif %}</nav>
{% endblock %}

Read the code

  1. The input name q produces the query parameter. urlencode preserves search characters when building pagination links.
  2. The for-empty branch handles a successful query with zero matches; it is not the same as a database failure.

templates/shop/product_detail.html

Show the selected product from the view context.

templates/shop/product_detail.html
{% extends "base.html" %}
{% block title %}{{ product.name }} · EduShop{% endblock %}
{% block content %}<h1>{{ product.name }}</h1><p>{{ product.description }}</p><p>₹{{ product.price }}</p><p>{{ product.stock }} available</p>{% endblock %}

Read the code

  1. A single record supplies the title, description and price. The template does not run another lookup.
  2. Stock is displayed here but not reserved. Later checkout checks it again when creating an order.

4. Run it and check your result

  • Search and page URLs can be pasted into another browser.
  • An unknown or inactive product returns 404.

5. Predict, change and observe

Create enough matching products for two pages, then follow the next-page link.

Compare your prediction with the expected result

What you should observe

The search term stays in the address and only matching products appear.

Why it happens

Pagination must carry the current filter state. A page number alone would switch back to the unfiltered catalog.

6. Troubleshoot with evidence

A common mistake

Do not pass arbitrary query text straight into order_by. Explicitly map public sort choices to allowed field names.

Search resets on page two

Likely cause: The next-page URL dropped q.

Check and correct: Generate links with both page and the encoded search value.

Hidden product remains accessible directly

Likely cause: Only the list query checks active=True.

Check and correct: Apply the visibility condition to get_object_or_404 in the detail view too.

7. Practice and explain it back

Your independent task

Add a price sort selector with an allowlist of supported database ordering fields.

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

Why not return an empty detail page?

A missing resource is a 404. An empty collection is a valid 200 response. These responses communicate different outcomes.

Is a template include a database query?

No. It renders context already provided to it. Avoid hiding database decisions inside presentation code.