In Django, routing is built around two closely related pieces: URL patterns and view functions. A URL pattern describes the shape of a URL and the rules Django uses to match it. A view function contains the code that should run after a request matches that pattern.
This routing mechanism makes it possible to match different parts of a URL and, when needed, extract values from the URL and pass them into the corresponding view function.
# myapp/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('about/', views.about, name='about'),
path('post/<int:post_id>/', views.post_detail, name='post_detail'),
]
In this example, the application defines three URL patterns:
- The empty path,
path(''), is mapped to theviews.homeview function. This usually represents the home page of the application. - The
about/path is mapped toviews.about, which can be used for an about page. - The
post/<int:post_id>/path is mapped toviews.post_detail. In this case, Django takes thepost_idvalue from the URL and passes it to the view function as an argument. The angle brackets mark the dynamic part of the URL, andintspecifies that the value should be treated as an integer.
The urlpatterns list contains all URL patterns for the application. Each pattern is defined with the path function. The first argument is the URL pattern as a string, and the second argument is the view function Django should call when the pattern is matched. A URL pattern can also be given a name, which makes it easier to refer to that route elsewhere in the project.
In most projects, an application’s URL configuration is included from the project-level URL file. For example, if the application is named myapp, the main URL configuration can include it like this:
# project/urls.py
from django.urls import include, path
urlpatterns = [
path('myapp/', include('myapp.urls')),
]
Here, the include function brings the URL patterns defined in myapp/urls.py into the main routing configuration. With this setup, when a user visits a path beginning with /myapp/, Django will continue resolving the request using the URL patterns defined inside the application.
This is only the basic structure of Django’s routing system. Django also supports more advanced routing features, including regular expression matching and namespaces. By defining URL patterns and connecting them to the appropriate view functions, you can organize request handling clearly and build a complete web application on top of Django’s URL dispatcher.