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
?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With