A Django urls.py module is the traffic map for a web application. When a web server passes an HTTP request to Django through WSGI, Django checks urlpatterns, finds a matching path, and calls its view. The file is ordinary Python, although renaming it is rarely useful. section 1.1.1 section 2.6
Keep the core mental model simple:
- urlpatterns is a list of Django path objects. section 1.1.1
- Each path maps a URL pattern to a callable view or loads another URL-mapping file. section 1.1.1 section 2.6
- The view receives the request, which can contain the URL, query parameters, HTTP method, headers, and form data. section 1.1.1
- Django supplies a default admin route; application routes are added alongside it. section 2.6
Registering a RiffMates view
The project-level file can register the home app’s credits view like this: from django.contrib import admin from django.urls import path from home import views as home_views urlpatterns = [ path("admin/", admin.site.urls), path("credits/", home_views.credits), ] A request for /credits/ matches the second path and calls home_views.credits. Importing the module and using an alias makes the central mapping easier to read when several apps have a views.py file. Do not add a leading slash to the pattern; Django supplies it. section 2.6
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
]
Use the route-registration listing as a compact reference for imports, the urlpatterns list, the admin mapping, and the credits mapping. section 2.6
