Francois Barnard
Francois Barnard

Reputation: 83

How do you implement Django namespaces

I have started my journey with Django and I am thoroughly loving it. I do have a question about namespaces which I hope someone will be able to help me with and explain why it works like that.

I understand namespaces are used to make sure that if you have two pages with the same name that the url and reverse function points to the right page. I have been trying to implement namespaces in a test app I am writing but have not been able to do it.

Here is what I have so far (This is without namespaces as I haven't been able to get it to work.

Extract from app urls.py

from django.urls import path, re_path
from . import views



urlpatterns = [

 path('', views.index, name = "index"),
]

project urls.py

from django.contrib import admin
from django.urls import path, include, re_path
import gallery



urlpatterns = [
    path('admin/', admin.site.urls),
    path('accounts/', include('django.contrib.auth.urls')),
    path('index/', include('gallery.urls')),
]

And lastly, this is my view.py file in my app folder

from django.shortcuts import render
from django.urls import reverse


# Create your views here.

def index(request):
    return render(request,"gallery/index.html")

Any help will be appreciated

Upvotes: 1

Views: 1083

Answers (1)

mirodil
mirodil

Reputation: 537

URL namespaces allow you to uniquely reverse named URL patterns even if different applications use the same URL names. It’s a good practice for third-party apps to always use namespaced URLs. Similarly, it also allows you to reverse URLs if multiple instances of an application are deployed. In other words, since multiple instances of a single application will share named URLs, namespaces provide a way to tell these named URLs apart. See URL namespaces

In your case:

project urls.py

from django.contrib import admin
from django.urls import path, include, re_path
import gallery



urlpatterns = [
    path('admin/', admin.site.urls),
    path('accounts/', include('django.contrib.auth.urls', namespace='your-namespace')),
    path('index/', include('gallery.urls',namespace='your-namespace')),
]

Extract from app urls.py

from django.urls import path, re_path
from . import views

app_name = 'app'
urlpatterns = [

 path('', views.index, name = "index"),
]

in the template:

{% url 'app:index' %}

Upvotes: 2

Related Questions