WHAT FOR? Namespacing URL names in tutorial

Hello!
I was reading the Tutorial, part 3.

I did not get, why

The tutorial project has just one app, polls. In real Django projects, there might be five, ten, twenty apps or more. How does Django differentiate the URL names between them? For example, the polls app has a detail view, and so might an app on the same project that is for a blog. How does one make it so that Django knows which app view to create for a url when using the {% url %} template tag?

Did not got the problem to be honest.
The user requests some URL, for example

polls/detail

or

blog/detail

So, it is clear, what application causes a view to begin

What for Namespacing URL names is needed then?
Give me an example please

The issue here doesn’t have much of anything to do with external URLs - it has more to do with the views and templates being able to reference or create references to the right url.

Assume for the moment that you have two apps - polls and research.

In your polls/urls.py file you have (among other entries) the following:

urlpatterns = [
   ...
   path("/results/", views.results, name="results"),
   ...
]

Now assume that in your research app, you have the following in research/urls.py

urlpatterns = [
   ...
   path("/results/", views.results, name="results"),
   ...
]

Finally, in your root urls.py file (perhaps mysite/urls.py as defined in the settings), you have the following:

urlpatterns = [
   ...
   path("polls/", include('polls.urls')),
   path("research/", include('research.urls')),
   ...
]

If you try to render {% url 'results' %}, which url are you going to get? Is it going to be /polls/results/ or will it be /research/results/? Regardless of which one you get, how would you reference the other one?

This is the issue that the URL namespacing resolves. By allowing you to specify {% url 'polls:results' %}, you’re specifying that you want to render the URL named results in the polls namespace.

Now, you might be tempted to say “This can’t happen”, but with installable apps written by third partities that you’re using in your project, how can you be sure?

You might not be the author of polls or of research, or both.

You might be installing third.party.app.one and different.party.app.four, and the two of them could have url conflicts between each of them, creating a problem that you can’t easily resolve. If those third-party app authors are using namespaces within their apps, they can prevent their app from conflicting with other apps.

3 Likes

Thank you Ken so much :heart_eyes:
Your example certainly needs to be included in the tutorial