Adding optional trailing_slash for SimpleRouter and test.

This does not break the previous behaviour, where trailing_slash can be only True or False. By default it stays True.
It adds an extra option: when trailing_slash=None (or any other value), the trailing_slash becomes optional.
This commit is contained in:
decadenza 2025-02-27 16:27:05 +00:00
parent 6fd8cd7f56
commit ba8e037951
2 changed files with 21 additions and 1 deletions

View File

@ -136,7 +136,12 @@ class SimpleRouter(BaseRouter):
]
def __init__(self, trailing_slash=True, use_regex_path=True):
self.trailing_slash = '/' if trailing_slash else ''
if trailing_slash is True:
self.trailing_slash = '/'
elif trailing_slash is False:
self.trailing_slash = ''
else:
self.trailing_slash = "/?"
self._use_regex = use_regex_path
if use_regex_path:
self._base_pattern = '(?P<{lookup_prefix}{lookup_url_kwarg}>{lookup_value})'

View File

@ -328,6 +328,21 @@ class TestTrailingSlashRemoved(TestCase):
assert expected[idx] == self.urls[idx].pattern.regex.pattern
class TestTrailingSlashOptional(TestCase):
def setUp(self):
class NoteViewSet(viewsets.ModelViewSet):
queryset = RouterTestModel.objects.all()
self.router = SimpleRouter(trailing_slash=None)
self.router.register(r'notes', NoteViewSet)
self.urls = self.router.urls
def test_urls_have_trailing_slash_by_default(self):
expected = ['^notes/?$', '^notes/(?P<pk>[^/.]+)/?$']
for idx in range(len(expected)):
assert expected[idx] == self.urls[idx].pattern.regex.pattern
class TestNameableRoot(TestCase):
def setUp(self):
class NoteViewSet(viewsets.ModelViewSet):