abuka123
abuka123

Reputation: 451

Why to use the extra slash (/) at the end of the Django urls?

I'm trying to create a REST API using Django. I'm currently implementing the urls.py file. In a lot of different examples, I saw that they add / at the end of the url. For example:

urlpatterns = [
    path('login/', obtain_auth_token, name='api_token_auth'),
]

I'm trying to figure way. Surely for login POST request which returns a token (given username and password), you want to access <domain>/api/login and not <domain>/api/login/. Currently I solved it with:

urlpatterns = [
    re_path(r'login$', obtain_auth_token, name='api_token_auth'),
]

Or:

urlpatterns = [
    path('login', obtain_auth_token, name='api_token_auth'),
]

But what is the convention? Why a lot of different examples add the extra / at the end? When do you want to add it?

Upvotes: 2

Views: 883

Answers (1)

Bernhard Vallant
Bernhard Vallant

Reputation: 50796

Django's CommonMiddleware tries to normalize URLs, so that every URL exists only once, not in a version ending with slash and one without. Therefore the user doesn't have to care about appending a slash or not, also for search engines this is a big win as they don't see the same content with different URLs. You can configure this behaviour either with the APPEND_SLASH setting or the no_append_slash() decorator.

Upvotes: 4

Related Questions