Django Namespacing and URL

Posted under » Django on 6 May 2021

Continued from Views - index and template, since you defined the name argument in the path() functions in the polls.urls module, you can remove a reliance on specific URL paths defined in your url configurations by using the {% url %} template tag: From

<li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>

To

<li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>

The way this works is by looking up the URL definition as specified in the polls.urls module. You can see exactly where the URL name of ‘detail’ is defined below:

path('<int:question_id>/', views.detail, name='detail'),

If you want to change the URL of the polls detail view to something else, perhaps to something like polls/specifics/12/ instead of doing it in the template (or templates) you would change it in polls/urls.py:

path('specifics/<int:question_id>/', views.detail, name='detail'),

In actual 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?

The answer is to add namespaces to your URLconf. In the polls/urls.py file, go ahead and add an app_name to set the application namespace:

from django.urls import path

from . import views

app_name = 'polls'
urlpatterns = [
    path('', views.index, name='index'),
    path('<int:question_id>/', views.detail, name='detail'),
    path('<int:question_id>/results/', views.results, name='results'),
    path('<int:question_id>/vote/', views.vote, name='vote'),
]

This can be improved by changing question_id to pk.

Now change your template from

<li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>
to
<li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>

web security linux ubuntu python django git Raspberry apache mysql php drupal cake javascript css AWS data