Last active
October 27, 2022 08:17
-
-
Save Trafitto/41d9ca73158df218175fe8b20d4b3f96 to your computer and use it in GitHub Desktop.
Django-Rest-Framework custom router that accept urls with or without slash at the end
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from rest_framework.routers import DefaultRouter | |
class OptionalTraillingSlashRouter(DefaultRouter): | |
def __init__(self, trailing_slash=True): | |
super().__init__(trailing_slash) | |
self.trailing_slash = "/?" | |
def get_lookup_regex(self, viewset): | |
base_regex = '(?P<{lookup_field}>[^/.]+)' | |
lookup_field = getattr(viewset, 'lookup_field', 'pk') | |
return base_regex.format(lookup_field=lookup_field) | |
''' | |
router = OptionalTraillingSlashRouter() | |
router.register(r'test', TestViewSet, basename='test') | |
# This router accept both url | |
# test/1/ | |
# test/1 | |
''' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment