🎓 A1Learner
🔍
0 of 50 lessons completed

Django URL Patterns

A URL pattern is a rule that pairs an address with a view. The list named urlpatterns holds the rules for a project.

Add the home pattern

This list holds one pattern. The empty string means the home address.

urlpatterns = [path("", home)]

Add a second pattern

A second pattern works the same way. It pairs about/ with its own view.

urlpatterns = [path("", home), path("about/", about)]

Ask for both pages

The test client visits each address and shows the page that comes back.

client = Client()
print(client.get("/").content.decode())
print(client.get("/about/").content.decode())

Check both status codes

Each address answers with the number 200. The number means each page arrived.

print(client.get("/").status_code)
print(client.get("/about/").status_code)

Example

import django
from django.conf import settings

settings.configure(DEBUG=True, SECRET_KEY="key", ROOT_URLCONF=__name__, ALLOWED_HOSTS=["*"])
django.setup()

from django.http import HttpResponse
from django.urls import path


def home(request):
    return HttpResponse("Home page")


def about(request):
    return HttpResponse("About page")


urlpatterns = [path("", home), path("about/", about)]

from django.test import Client

client = Client()
print(client.get("/").content.decode())
print(client.get("/about/").content.decode())

Key points

  • A URL pattern pairs an address with a view function.
  • The path function makes one pattern.
  • The first path argument is the address string.
  • The second path argument is the view function.
  • One project holds many patterns, one per address.

In this example, the setup lines configure Django. The home view returns Home page, and the about view returns About page. The pattern list pairs each address with its view. The test client visits each address and shows the page that comes back.

Note

The home address is an empty string inside path.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does urlpatterns hold?