0
0
Djangoframework~5 mins

URL namespacing in Django

Choose your learning style9 modes available
Introduction

URL namespacing helps organize and avoid confusion when you have many URLs in a Django project. It lets you group URLs under a common name.

When your project has multiple apps with similar URL names.
When you want to refer to URLs clearly in templates or views.
When you want to avoid URL name conflicts between apps.
When you want to keep your URL structure clean and organized.
Syntax
Django
In your main urls.py:

path('app1/', include(('app1.urls', 'app1'), namespace='app1')),

In app1/urls.py:

app_name = 'app1'

urlpatterns = [
    path('home/', views.home, name='home'),
]

Use in templates or views:

{% url 'app1:home' %}

The namespace groups URLs under a name.

Use app_name in app urls.py to define the app's namespace.

Examples
This example shows two apps, blog and shop, each with their own namespace.
Django
In project urls.py:

from django.urls import path, include

urlpatterns = [
    path('blog/', include(('blog.urls', 'blog'), namespace='blog')),
    path('shop/', include(('shop.urls', 'shop'), namespace='shop')),
]
Defines the app_name for the blog app and a URL named 'post_detail'.
Django
In blog/urls.py:

from django.urls import path
from . import views

app_name = 'blog'

urlpatterns = [
    path('post/<int:id>/', views.post_detail, name='post_detail'),
]
Uses the namespaced URL to link to a blog post with id 5.
Django
In a template:

<a href="{% url 'blog:post_detail' id=5 %}">Read Post</a>
Sample Program

This example shows how to set up URL namespacing for a 'store' app. The URL 'store/products/' calls the products view. In templates, you use 'store:products' to link to this URL.

Django
### project/urls.py ###
from django.urls import path, include

urlpatterns = [
    path('store/', include(('store.urls', 'store'), namespace='store')),
]


### store/urls.py ###
from django.urls import path
from . import views

app_name = 'store'

urlpatterns = [
    path('products/', views.products, name='products'),
]


### store/views.py ###
from django.http import HttpResponse

def products(request):
    return HttpResponse('Welcome to the products page!')


### Usage in template ###
# <a href="{% url 'store:products' %}">Products</a>
OutputSuccess
Important Notes

Always set app_name in your app's urls.py when using namespaces.

Namespaces help avoid clashes when different apps have URLs with the same name.

Use the namespaced name in templates and views to refer to URLs clearly.

Summary

URL namespacing groups URLs under a common name to keep them organized.

It prevents name conflicts between apps with similar URL names.

Use namespace in include() and app_name in app urls.py.