Optional tailing slash with Django

Fanciful Moment

The default urls of Django must include a tailing slash, otherwise, the framework will not recognize the url. But according to the user’s preference, the tailing slash will not be given most of the time. Here is the solution to change this rule. We can use the regex to match the tailing slash whatever it exists or not.

With rest_framework router

optional tailing slash with router
1
2
3
4
5
6
7
8
9
10
11
12

import viewsets
from rest_framework import SimpleRouter

class OptionalSimpleRouter(SimpleRouter):
def __init__(self)
super().__init__()
self.tailing_slash = '/?'

router = OptionalSimpleRouter()
router.register(r'test', viewsets.TestViewSet, basename='test')

With django path

optional tailing slash with re_path
1
2
3
4
5
6

import views
from django.urls import re_path

re_path(r'test/?$', views.TestView, basename='test')

Refrences:

[1] https://stackoverflow.com/questions/59115733/how-to-make-trailing-slash-optional-in-django

[2] https://stackoverflow.com/questions/46163838/how-can-i-make-a-trailing-slash-optional-on-a-django-rest-framework-simplerouter


Optional tailing slash with Django
https://r-future.github.io/post/optional-tailing-slash-with-django/
Author
Future
Posted on
July 12, 2022
Licensed under