Chapter 4 · 10 min read
URLs and Views
URLs and Views
Every web page you visit starts with a request, and Django answers it with a view. This chapter shows how an address typed in the browser finds the right Python function.
What you will learn
- How Django matches a URL to a view.
- How to write function-based views that return a response.
- How to capture values from the URL with path converters.
- How to split URLs between the project and an app with
include(). - Why URL names and namespaces matter.
The request journey
- The browser asks for an address, for example
/hello/Samir/. - Django reads the root URL table,
config/urls.py, from top to bottom. - The first
path()rule that matches wins. Aninclude()hands the rest of the address to an app's ownurls.py. - The matching view runs. It receives an
HttpRequestobject and must return anHttpResponse. - Django sends the response to the browser.
If no rule matches, Django returns a 404 page. While DEBUG is on, that 404 page lists every rule Django tried, which is very helpful for debugging.
What a view is
A view is just a Python function with at least one parameter, usually named request. Whatever it returns is sent to the visitor.
from django.http import HttpResponse
def home(request):
return HttpResponse("Hello, Django!")
The HttpResponse class builds a response from a string. Later you will use templates and render() to build full HTML pages.
Step by step
1. Write two views
Open blog/views.py and replace its content:
from django.http import HttpResponse
def home(request):
return HttpResponse("Hello, Django!")
def hello(request, name):
return HttpResponse(f"Hello, {name}!")
The second view takes an extra parameter, name. Django fills it from the URL.
2. Create the app's URL table
Create a new file blog/urls.py:
from django.urls import path
from . import views
app_name = "blog"
urlpatterns = [
path("", views.home, name="home"),
path("hello/<str:name>/", views.hello, name="hello"),
]
Line by line:
from . import viewsimports theviews.pynext to this file.app_name = "blog"gives these URLs a namespace. You will refer to them asblog:homeandblog:hello, so names never clash between apps.urlpatternsis the list Django reads. Eachpath(route, view, name=...)has three parts: the address pattern, the view to call, and a name for reverse lookups.<str:name>is a path converter. It matches any non-empty text without a slash and passes it to the view as the keyword argumentname.
3. Connect the app to the project
Replace config/urls.py with:
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path("admin/", admin.site.urls),
path("", include("blog.urls")),
]
include("blog.urls") says: for everything that was not matched earlier, hand the rest of the address to the blog app. The empty route "" means the blog app lives at the site root.
Path converters
| Converter | Matches | Example |
|---|---|---|
str | any non-empty text without / (the default) | hello/<str:name>/ |
int | zero or a positive whole number | post/<int:pk>/ |
slug | letters, digits, hyphens and underscores | tag/<slug:tag>/ |
uuid | a formatted UUID | item/<uuid:id>/ |
path | any text, including slashes | files/<path:name> |
Choose the strictest converter that fits. With <int:pk>, the address /post/abc/ does not match at all and gives a 404 instead of crashing your view.
Naming URLs and reversing them
Hard-coding addresses in templates and views makes changing them painful. Instead, give each pattern a name and look it up:
from django.urls import reverse
reverse("blog:hello", kwargs={"name": "Samir"}) # '/hello/Samir/'
In templates the same job is done with the url tag, which you will use in the next chapter.
Check it works
Start the server with python manage.py runserver and visit:
- http://127.0.0.1:8000/ shows
Hello, Django!. - http://127.0.0.1:8000/hello/Samir/ shows
Hello, Samir!. - http://127.0.0.1:8000/nothing/ shows Django's yellow 404 page with the list of tried URLs.
Exercises with solutions
Exercise 1: an about page
Add /about/ that returns one sentence about you.
Solution. In blog/views.py:
def about(request):
return HttpResponse("I am learning Django 6.1.")
In blog/urls.py add to the list:
path("about/", views.about, name="about"),
Exercise 2: a calculator
Add /add/2/3/ that shows the sum 5.
Solution. View:
def add(request, a, b):
return HttpResponse(str(a + b))
URL:
path("add/<int:a>/<int:b>/", views.add, name="add"),
HttpResponse needs text, so convert the number with str(). Because the converters are int, Django passes real integers, so a + b adds them.
Exercise 3: use the request
Add /method/ that tells the visitor which HTTP method they used.
Solution.
def method(request):
return HttpResponse(f"You used {request.method}")
path("method/", views.method, name="method"),
Visiting it in the browser prints You used GET. request.method is "GET" for page loads and "POST" for submitted forms, which you will use in the forms chapter.
Common mistakes
- Forgetting the comma between list items or after a
path(). Python raises aSyntaxError. - Forgetting
include()or an import. The page 404s, or Python raisesImportError. - A view that returns nothing. Django reports "The view didn't return an HttpResponse object". Always
returnsomething. - Mixing up the two
urls.pyfiles.config/urls.pyis the project's;blog/urls.pyis the app's. - Using
<str:...>where a number is needed. Use<int:...>so only digits match. - Forgetting the trailing slash in the browser. With default settings, Django redirects
/aboutto/about/only if the pattern ends with a slash.
Key takeaways
- A URLconf maps addresses to views; the first matching rule wins.
- A view takes a request and returns a response.
- Path converters capture parts of the URL as arguments.
include()andapp_namekeep each app's URLs organised and namespaced.- Name your URLs and use
reverse()or{% url %}instead of hard-coding addresses.
Official links
- URL dispatcher: https://docs.djangoproject.com/en/6.1/topics/http/urls/
- Writing views: https://docs.djangoproject.com/en/6.1/topics/http/views/
- Tutorial part 3: https://docs.djangoproject.com/en/6.1/intro/tutorial03/
