Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't you pass just an `app_name` keyword arg when including another URLconf?

Tags:

django

In the standard urls.py of a Django app, if I pass an app_name without a namespace into an include() call, like below:

urlpatterns = [
    # ...
    url(r'^', include('foo.urls', app_name='foo')),
    # ...
]

I get a error like below when hitting one of the included urls.

ValueError: Must specify a namespace if specifying app_name.

So it's necessary to do:

urlpatterns = [
    # ...
    url(r'^', include('foo.urls', namespace='foo-urls', app_name='foo')),
    # ...
]

I don't see the hard dependency between the two; why is it necessary to specify a namespace in order to be able to specify an app_name?

like image 526
James Hiew Avatar asked Mar 11 '23 14:03

James Hiew


1 Answers

If you are using the namespace attribute in the include function, you must define app_name in the application urls.py file you are using. > Django 2.0 URL dispatcher documentation
For instance, if this is your project structure:

project/
├── app1
│   └── urls.py
├── app2
│   └── urls.py
└── project
    └── urls.py

And you want to include (app1, app2) urls, you first must define app_name in app1/urls.py and app2/urls.py:

file: app1/urls.py:

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

file: app2/urls.py:

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

file: project/urls.py:

urlpatterns = [  
    path('', include('app1.urls', namespace='app1')),
    path('', include('app2.urls', namespace='app2')),
]

So, you can now use something like this {% url 'app1:home' %} or {% url 'app2:home' %} in your template file.

like image 119
Jorge F. Sanchez Avatar answered May 12 '23 16:05

Jorge F. Sanchez