Chapter 6 of 12
Django's URL routing system maps URL patterns to views. URL patterns use Python's regex or path converters to match incoming URLs.
from django.urls import path
from . import views
# Name each URL so you can reference it by name, not string
urlpatterns = [
path("", views.course_list, name="course-list"),
path("<slug:slug>/", views.course_detail, name="course-detail"),
path("api/courses/", views.course_api, name="course-api"),
]from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path("admin/", admin.site.urls),
path("courses/", include("courses.urls")),
path("blog/", include("blog.urls")),
path("api/", include("api.urls")),
]
# URL resolution:
# Request: GET /courses/nextjs/
# Django finds "courses/" โ includes courses/urls.py
# Matches "<slug:slug>/" โ calls course_detail(request, slug="nextjs")| Converter | Matches | Example |
|---|---|---|
| str | Any non-empty string (no slashes) | <str:username> |
| int | Positive integers | <int:id> |
| slug | Letters, numbers, hyphens, underscores | <slug:slug> |
| uuid | UUID strings | <uuid:uuid> |
| path | Any string including slashes | <path:file_path> |