djangodjango-templatesdjango-urls

python- Django : Where does Django "Append a Slash"?


I was wondering about...

If I have an application called magazine, and its urlpatterns inside urls.py is like this :

from django.urls import path
from . import views

path("articles/<int:pk>", views.get_article, name="article")

.. without a trailer slash, then Django should "append a slash" by default, right?

Where is this slash appended?

I mean is it added only when I handwrite the url in the browser?

I mean if there was an anchor tag in a template like this :

<a href="{% url 'magazine:article' 5 %}"> Article 5 </a>

.. Wouldn't it go and get the path above without a trailer slash, and then an error with Not Found?

Does this APPEND_SLASH setting mean that I can't, or it's impossible to reach that link above without adding a trailer slash at the end?


Solution

  • The slash is not appended. It thus means that you can visit this page with /arcticles/5 for example (to access the article with primary key 5).

    Django has an APPEND_SLASH settingĀ [Django-doc]. If this is set to True (the default), it will first try to match a path with the given URL patterns, and if that fails, append a slash and search again.

    It makes more sense to use a trailing path however, so I would advise to rewrite the path to:

    path('articles/<int:pk>/', views.get_article, name='article')