I am having a difficult time understanding the connection between app_name and namespace.
consider the project level urls.py
from django.urls import path, include
urlpatterns = [
path('blog/', include('blog.urls', namespace='blog')),
]
consider the app level (blog) urls.py
from django.urls import path
from . import views
app_name = 'blog'
urlpatterns = [
path('', views.post_list, name='post_list'),
path('<int:year>/<int:month>/<int:day>/<slug:post>/', views.post_detail, name='post_detail'),
]
if I comment out app_name, I get the following.
'Specifying a namespace in include() without providing an app_name '
django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in
the included module, or pass a 2-tuple containing the list of patterns and app_name instead.
If I rename app_name to some arbitrary string, I don't get an error.
app_name = 'x'
I've read the documentation but its still not clicking. Can someone tell me how/why app_name and namespace are connected and why are they allowed to have different string values? Isn't manually setting app_name redundant?
The app_name can be used as a default application namespace, if defined in the urls.py .
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 (as we did in the tutorial). Similarly, it also allows you to reverse URLs if multiple instances of an application are deployed.
Every URLConf module must contain a variable urlpatterns which is a set of URL patterns to be matched against the requested URL. These patterns will be checked in sequence, until the first match is found. Then the view corresponding to the first match is invoked.
URLconf is a set of patterns that Django will try to match the requested URL to find the correct view.
try removing app_name='blog'
In your case you should be using:
'blog:post_list'
and
'blog:post_detail'
You can also remove the namespace='blog'
in your first url like so:
urlpatterns = [
path('blog/', include('blog.urls')),
]
and then in your templates you can reference the urls without the 'blog:.....':
'post_list'
'post_detail'
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