A URL routing file is a Python module that maps URL patterns to views. In Django, an app-specific file keeps an app’s routes together instead of making the project-level file manage every view. section 4.6.1
A typical routing setup works like this:
- Define an app route with path(), optionally capturing typed arguments such as <int:musician_id>. section 4.6.1
- Register the app’s module in the project-level urls.py with include(). section 4.6.1
- Django combines the project prefix with each app route, so bands/ plus musician/<int:musician_id>/ reaches the musician view. section 4.6.1
Listing 4.5 App specific URL pattern declaration file for bands
# RiffMates/bands/urls.py
from django.urls import path
from bands import views
urlpatterns = [
path('musician/<int:musician_id>/', views.musician, name="musician"), #1
]
Shows the bands app’s URL pattern, including an integer argument passed to its view. section 4.6.1
Listing 4.6 Registering all the URL routes in the bands app
# RiffMates/RiffMates/urls.py
...
from django.urls import path, include #1
...
urlpatterns = [
...
path('bands/', include("bands.urls")), #2
]
Shows how the project-level URL file includes the bands route namespace under the bands/ prefix. section 4.6.1
