[Solved]-How to make trailing slash optional in django

12👍

You can use re_path instead of path for use regular expression in your url pattern. use ? sign in your url like this:

from django.urls import re_path
re_path(r'url/?$', views.appmain, name="main")

Note: question mark matches zero or one / in the url. it accepts both domain.com/url and domain.com/url/

2👍

Not a direct answer to the question, but may save headache for someone with case similar to mine.

Trailing slash is optional by default because of APPEND_SLASH setting (if you include CommonMiddleware), and it makes Django redirect 'url' to 'url/' (if 'url' is not a valid url pattern itself).
For some specific reasons I needed optional trailing slash without redirect, so I came to re_path(r'^url/?$', ...) option mentioned above, and it works. BUT – redirects from APPEND_SLASH are 301 Permanent, so for your new url config to start working without redirect, you need to turn on "Disable cache" in browser devtools Networking tab.

👤Yarrow

Leave a comment