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.
PROJECT 3 · LESSON 6 OF 16
Read database records into reusable templates and handle missing products.
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.
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.
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.
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.
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.
Read this sequence before the source. Identify the input, the component or function that handles it, and the result the learner sees.
GET /products/?q=note&page=1 reaches the catalog view.
The view filters active products and applies optional search.
Paginator selects the requested slice.
The template loops over that slice and includes a card for each product.
A detail link sends a new request, which looks up one active slug or returns 404.
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.
Add collection and detail reads to the existing business-site views.
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})
Expose collection and slug-based product routes.
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"),
]
Provide the shared HTML document, navigation and content slots.
{% 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>
Render one catalog item with a named details link.
<article><h2><a href="{% url 'shop:product-detail' product.slug %}">{{ product.name }}</a></h2><p>{{ product.description }}</p><strong>₹{{ product.price }}</strong></article>
Keep search and paging state in shareable GET parameters.
{% 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 %}
Show the selected product from the view context.
{% 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 %}
Create enough matching products for two pages, then follow the next-page link.
The search term stays in the address and only matching products appear.
Pagination must carry the current filter state. A page number alone would switch back to the unfiltered catalog.
Do not pass arbitrary query text straight into order_by. Explicitly map public sort choices to allowed field names.
Likely cause: The next-page URL dropped q.
Check and correct: Generate links with both page and the encoded search value.
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.
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.
A missing resource is a 404. An empty collection is a valid 200 response. These responses communicate different outcomes.
No. It renders context already provided to it. Avoid hiding database decisions inside presentation code.