The urls.py file is responsible for URL routing in Django. It maps incoming HTTP requests to the appropriate view functions based on the requested URL. Django supports two levels of URL configuration: project-level and app-level.
include() enables reusable URL patternsThe project-level urls.py is located in the main project directory. It includes URL configurations from individual apps.
// Project-level urls.py configuration
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('blog/', include('blog.urls')),
]
This setup forwards all /blog/ requests to the blog app’s URL configuration.
Each Django app can define its own urls.py containing routes specific to that app.
// App-level urls.py for blog app
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('post/<int:id>/', views.post_detail, name='post_detail'),
]
The include() function helps modularize URL routing by delegating URL handling to apps.
// Including multiple apps at project level
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('blog/', include('blog.urls')),
path('shop/', include('shop.urls')),
]
// URL request flow demonstration
Browser Request → project urls.py → include() → app urls.py → view function
Type a URL path to see how Django resolves it:
urlpatterns...include(): Handing off to blog.urls...urls.py