Gjert
Gjert

Reputation: 1067

Making nested namespaces in a single Django 2 app

I'm trying to create nested namespaces in my application in Django 2. I'm aware that I am required to use app_name in my urls.py file, but my question is, how would I do it if I wish to nest multiple namespaces in a single app?

My app is called account and I wish to be able to reverse the following: account:index, account:edit:index, account:create:index, account:edit:email:index and so on. How would I approach this in Django 2?

Here is a simplified version of what I have tried so far, without success.

In my account.urls file

app_name = 'account'

email_url = [
    path('', edit_email, name='index')
]

edit_url = [
    path('', edit, name='index'),
    path('email/' include(email_url, namespace='email'))
]

create_url = [
    path('', create, name='index'),
]

urlpatterns = [
    path('', index, name='index'),

    # edit
    path('edit/', include(edit_url, namespace='edit')),

    # create
    path('create/', include(create_url, namespace='create')),
]

In my root urls file:

urlpatterns = [
    path('admin/', admin.site.urls),
    path('account/', include('account.urls', namespace='account')),
]

Upvotes: 1

Views: 1348

Answers (1)

Percy
Percy

Reputation: 46

Check the include Docs

include((pattern_list, app_namespace), namespace=None)

pattern_list followed by app_namespace

You have to define app_namespace, not namespace

I've done a similar project you did, and it works.

# top level urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('accounts/', include('accounts.urls', namespace='account')),
]

# accounts/urls.py
from django.urls import path, include
from .views import index, create_index, edit_index
app_name = 'accounts'

create_url =[
    path('index/', create_index, name='index'),
]

edit_url =[
    path('index/', edit_index, name='index'),
]


urlpatterns = [
    path('', index, name='index'),
    path('edit/', include((edit_url,'edit'))),
    path('create/', include((create_url, 'create'))),
]

# templates/accounts/index.html
{% url 'accounts:index' %}<br/>
{% url 'accounts:edit:index' %}<br/>
{% url 'accounts:create:index' %}<br/>

# on the website
/accounts/
/accounts/edit/index/
/accounts/create/index/

I hope this helps you. Have fun!

Upvotes: 3

Related Questions