python / intermediate
Snippet
Django URL Configuration with Namespace and Names
URL namespacing in Django prevents name collisions when multiple apps use similar URL names like 'home' or 'detail'. The app_name variable in app's urls.py combined with namespace in project urls.py creates the 'app:name' pattern. This separation means shop:home and blog:home are distinct and won't conflict. In templates, use {% url 'namespace:name' args %} syntax. In Python code, django.urls.reverse() generates URLs. Named URL patterns improve maintainability: changing a URL path only requires updating the pattern, not every template or view that references it. Django's admin uses this pattern heavily for extensibility.
snippet.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# project/urls.pyfrom django.urls import path, includeurlpatterns = [path('shop/', include('shop.urls', namespace='shop')),path('blog/', include('blog.urls', namespace='blog')),]# shop/urls.pyfrom django.urls import pathfrom . import viewsapp_name = 'shop' # Enables namespacingurlpatterns = [path('', views.home, name='home'),path('products/<int:pk>/', views.product_detail, name='product-detail'),path('category/<slug:slug>/', views.category_view, name='category'),]# blog/urls.pyapp_name = 'blog'urlpatterns = [path('', views.post_list, name='post-list'),path('<int:year>/<int:month>/<slug:slug>/', views.post_detail, name='post-detail'),]# Template usage:# <a href="{% url 'shop:product-detail' product.id %}">View Product</a># <a href="{% url 'blog:post-detail' post.date.year post.date.month post.slug %}"># Reverse in Python:# from django.urls import reverse# url = reverse('shop:product-detail', kwargs={'pk': 42})
django
Breakdown
1
namespace='shop'
Project-level namespace grouping for URL patterns
2
app_name = 'shop'
App-level identifier enabling 'shop:url-name' referencing
3
{% url 'shop:product-detail' product.id %}
Template tag references namespaced URL with positional argument