URL Namespacing & App URLs
As projects grow, you need URL namespacing to avoid name collisions between apps. Django's include() with app_name creates isolated URL namespaces, keeping your routing clean and modular.
15 min•By Priygop Team•Updated 2026
Namespacing Concepts
- Each app should have its own urls.py
- Set app_name in the app's urls.py for namespacing
- Use include() in project urls.py to mount app URLs
- Reference namespaced URLs: 'app_name:url_name'
- Instance namespaces for multiple instances of the same app
- Keep project urls.py minimal — delegate to app urls.py files
Namespacing Example
Namespacing Example
# Project structure:
# mysite/urls.py (project-level)
# blog/urls.py (app-level)
# shop/urls.py (app-level)
# accounts/urls.py (app-level)
# mysite/urls.py — Project URL configuration
# from django.contrib import admin
# from django.urls import path, include
# urlpatterns = [
# path('admin/', admin.site.urls),
# path('blog/', include('blog.urls')),
# path('shop/', include('shop.urls')),
# path('accounts/', include('accounts.urls')),
# path('', include('pages.urls')), # Homepage
# ]
# blog/urls.py
# from django.urls import path
# from . import views
# app_name = 'blog'
# urlpatterns = [
# path('', views.list_view, name='list'),
# path('<int:pk>/', views.detail_view, name='detail'),
# ]
# shop/urls.py
# app_name = 'shop'
# urlpatterns = [
# path('', views.product_list, name='list'),
# path('<int:pk>/', views.product_detail, name='detail'),
# ]
# Both apps have 'list' and 'detail' — no conflict!
# {% url 'blog:list' %} -> /blog/
# {% url 'shop:list' %} -> /shop/
# {% url 'blog:detail' pk=1 %} -> /blog/1/
# {% url 'shop:detail' pk=1 %} -> /shop/1/Tip
Tip
Add Meta class to models for ordering, indexes, constraints: class Meta: ordering = ['-created_at']. This applies to all QuerySets.
Diagram
Loading diagram…
QuerySets are LAZY — no DB hit until evaluated.
Common Mistake
Warning
Not using db_index=True on fields you filter/order by frequently. Missing indexes cause slow queries on large tables.
Practice Task
Note
(1) Add Meta ordering to a model. (2) Create a custom manager. (3) Add db_index to a frequently queried field.
Quick Quiz
Key Takeaways
- As projects grow, you need URL namespacing to avoid name collisions between apps.
- Each app should have its own urls.py
- Set app_name in the app's urls.py for namespacing
- Use include() in project urls.py to mount app URLs