Skip to lesson content

PROJECT 1 · LESSON 2 OF 16

Add routes and understand requests

Build About and a parameterized greeting using explicit URL configuration.

  • URLconf
  • path converters
  • request
  • response

Your workspace: edushop

Continue from lesson 1: Install Django and serve Hello World. 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 store needs many addresses. URL routing gives each address a clear meaning and connects it to the function that handles it. Understanding this connection now makes product detail, edit and checkout routes much easier later.

Django routes are explicit Python mappings. Unlike Next.js, adding a folder does not create a URL. A view runs only after a matching pattern selects it.

The greeting demonstrates input from a URL. We will not use raw string interpolation to render untrusted HTML.

Match a route, then call a function

Django URL patterns are explicit Python declarations. Creating a file does not automatically create a route. config/urls.py is the entry point; include forwards the remaining path to shop/urls.py. This separates site-wide configuration from shop-specific addresses. Read the two URL files together when tracing a request.

A path converter such as <str:name> captures one path segment and passes it to the view using the same parameter name. The greeting view therefore receives request and name. A missing segment cannot satisfy the pattern, so Django continues checking other patterns and ultimately returns 404 if none match.

Path values and query strings solve different problems

A path value identifies the resource or route: /hello/Asha/ selects a greeting for Asha. A query string such as ?q=book supplies optional input to a selected route. Django places query parameters in request.GET; it does not pass them as extra positional view arguments. Later /products/notebook/ identifies a product, while /products/?q=note filters a collection.

URL input is user-controlled. A path converter establishes a basic shape, not permission or business validity. An integer converter cannot prove that a task belongs to the visitor. A slug converter cannot prove that a product exists. Those checks belong in the view and database lookup.

Name routes before linking many pages

A URL name is a stable application identifier. Templates can ask for shop:home rather than duplicate a literal address. app_name creates the shop namespace, so another app can also have a home or list route without ambiguity. Renaming the path then requires fewer edits.

Return an HttpResponse rather than a plain Python string. A response carries a body, status and headers. Our user-supplied greeting uses text/plain so a name containing angle brackets remains text. In later HTML templates, automatic escaping will handle ordinary variable output. Do not turn escaping off to make input look like HTML.

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. Django reads the incoming path without its query string.

  2. The root URLconf delegates to shop.urls.

  3. The greeting pattern captures a name and calls the matching view.

  4. The view constructs a plain-text response.

  5. An unmatched address returns 404 instead of calling an unrelated function.

Compare three addresses

  1. Visit the home address and observe the home response.
  2. Visit /hello/Asha/ and identify where Asha enters the view.
  3. Visit /missing/ and observe 404. The server is working; the address has no matching route.

3. Build it, one file at a time

  1. Replace shop/urls.py and shop/views.py. Keep the project include in config/urls.py.
  2. Visit /about/ and /hello/Praveen/. Watch how the captured name reaches the view.
  3. Try /missing/ and compare a route not found with the valid greeting.

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/urls.py

Declare the website’s three 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"),
]

Read the code

  1. path converters capture a segment and pass it by keyword to the view. Here the view parameter must be named name.
  2. The route strings have no leading slash. Use the trailing slash consistently in browser URLs.

shop/views.py

Handle different requests with focused view functions.

shop/views.py
from django.http import HttpResponse

def home(request):
    return HttpResponse("<h1>Hello, Django!</h1><p>My first working website.</p>")

def about(request):
    return HttpResponse("<h1>About EduShop</h1><p>Practical supplies for learners.</p>")


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

Read the code

  1. Each view accepts request first. greeting also receives the captured name from the URL dispatcher.
  2. The greeting explicitly uses text/plain so a supplied string is not interpreted as HTML. Templates later provide normal autoescaped HTML output.

4. Run it and check your result

  • /about/ displays its own heading; /hello/Asha/ returns Hello, Asha! as text.
  • /missing/ returns a not-found response.

5. Predict, change and observe

Change a route path while keeping its name, then visit the old address.

Compare your prediction with the expected result

What you should observe

The old address returns 404 unless another pattern matches it.

Why it happens

A route name helps reverse URL generation; it does not automatically create redirects from earlier addresses.

6. Troubleshoot with evidence

A common mistake

A route argument and its view parameter must have matching names. A mismatch produces an unexpected-keyword error.

Unexpected keyword argument in a view

Likely cause: The captured parameter name and function signature differ.

Check and correct: Match <str:name> to def greeting(request, name).

404 on a route you added

Likely cause: The app URLconf is not included or the path differs.

Check and correct: Trace config/urls.py to shop/urls.py and check trailing slashes and prefixes.

7. Practice and explain it back

Your independent task

Add /help/ and give it the route name help.

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

Does a URL parameter make a database query?

No. It only extracts input. You must explicitly query a model when the feature requires stored data.

Why split the URL configuration?

The project chooses where apps are mounted. Each app owns its internal routes, which keeps later task and order routes understandable.