Django’s include() function allows you to modularize your URL routing, keeping it organized and scalable as your project grows.
urls.py cleanThe include() function imports URL patterns from other urls.py files and attaches them to a URL path prefix.
// Import include and path helpers
from django.urls import include, path
urlpatterns = [
path('blog/', include('blog.urls')), // Routes blog URLs
path('shop/', include('shop.urls')), // Routes shop URLs
]
Here’s an example setup with two apps, blog and shop:
// Main project URL configuration
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls), // Admin route
path('blog/', include('blog.urls')), // Blog app URLs
path('shop/', include('shop.urls')), // Shop app URLs
]
// Blog application routes
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='blog_index'), // Blog home
path('<int:id>/', views.post_detail, name='post_detail'), // Blog post detail
]
// Shop application routes
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='shop_index'), // Shop home
path('product/<int:id>/', views.product_detail, name='product_detail'), // Product detail
]
// URL resolution flow
/blog/ → project urls.py → blog/urls.py → blog views
/shop/ → project urls.py → shop/urls.py → shop views
Type a URL to see how Django resolves it using include():
blog/, blog/5, shop/, shop/product/12urls.py inside each app.blog and shop).urls.py files.include() in project-level routing.