A path object is one entry in Django’s URL routing table. It pairs a URL pattern with the code that should handle a matching request—usually a view function, though it can also point to another URL-mapping file. Put path objects in the urlpatterns list in urls.py, and Django uses that list as its map from browser URLs to response handlers. section 1.1.1 section 1.1
When a browser visits a Django-controlled URL, the web server passes request information to Django through WSGI. Django checks its URL patterns for a match, then calls the associated view. The view receives the request and produces a response; no matching path means a 404 page instead. A path object is therefore the small but important signpost between “someone visited this address” and “run this Python code.” section 2.6 section 1.1
Register a credits page
To make a credits view reachable at credits/, import its views module and add a path object to urlpatterns: from home import views as home_views urlpatterns = [ path("admin/", admin.site.urls), path("credits/", home_views.credits), ] The first argument is the URL pattern. The second is the callable view function itself, not the result of calling it. Django supplies the leading slash, so write credits/ rather than /credits/. Aliasing the imported views module as home_views also keeps a central urls.py readable when several apps each have a views.py file. section 2.6
A path object can support a few practical routing patterns:
- Map a URL pattern directly to a function-based or class-based Django view. section 1.1.1
- Map to another URL-mapping file, allowing URL definitions to form a hierarchy rather than one giant list. section 1.1.1 section 2.6
- Use a mapping name elsewhere in Python or HTML so Django can substitute the URL, keeping a later URL change in one place. section 1.1
Listing 2.3 Register your view
# RiffMates/RiffMates/urls.py
from django.contrib import admin
from django.urls import path
from home import views as home_views #1
urlpatterns = [
path("admin/", admin.site.urls),
path('credits/', home_views.credits), #2
]
This listing shows the central urlpatterns list with Django Admin’s existing route and a new credits/ route pointing to home_views.credits. section 2.6
