NelsonLabs
Django/URL Routing

URL Routing

Django's URL routing system maps URL patterns to views. URL patterns use Python's regex or path converters to match incoming URLs.

courses/urls.py
python
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"),
]
myproject/urls.py โ€” include app URLs
python
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")

Path converters

ConverterMatchesExample
strAny non-empty string (no slashes)<str:username>
intPositive integers<int:id>
slugLetters, numbers, hyphens, underscores<slug:slug>
uuidUUID strings<uuid:uuid>
pathAny string including slashes<path:file_path>