How can I make a trailing slash optional on a Django Rest Framework SimpleRouter

后端 未结 5 1984
死守一世寂寞
死守一世寂寞 2021-02-05 02:43

The docs say you can set trailing_slash=False but how can you allow both endpoints to work, with or without a trailing slash?

相关标签:
5条回答
  • 2021-02-05 02:57

    I found the easiest way to do this is just to set up your URLs individually to handle the optional trailing slash, e.g.

    from django.urls import re_path
    
    urlpatterns = [
        re_path('api/end-point/?$', api.endPointView),
        ...
    

    Not a DRY solution, but then it's only an extra two characters for each URL. And it doesn't involve overriding the router.

    0 讨论(0)
  • 2021-02-05 03:00

    You can also override this setting by passing a trailing_slash argument to the SimpleRouter constructor as follows:

    from rest_framework import routers
    
    router = routers.SimpleRouter(trailing_slash=False)
    
    0 讨论(0)
  • 2021-02-05 03:11

    For anyone using rest_framework_extensions with ExtendedSimpleRouter, the accepted solution needs a small modification. The self.trailling_slash has to be after the super() like this.

    from rest_framework_extensions.routers import ExtendedSimpleRouter
    
    class OptionalSlashRouter(ExtendedSimpleRouter):
        def __init__(self):
            super(ExtendedSimpleRouter, self).__init__()
            self.trailing_slash = "/?"
    
    0 讨论(0)
  • 2021-02-05 03:13

    If you're using DRF's routers and viewsets, you can include /? in your prefix.

    from rest_framework import routers
    
    from .views import ClientViewSet
    
    router = routers.SimpleRouter(trailing_slash=False)
    router.register(r"clients/?", ClientViewSet)
    
    0 讨论(0)
  • 2021-02-05 03:16

    You can override the __init__ method of the SimpleRouter class:

    from rest_framework.routers import SimpleRouter
    
    
    class OptionalSlashRouter(SimpleRouter):
    
        def __init__(self):
            super().__init__()
            self.trailing_slash = '/?'
    

    The ? character will make the slash optional for all available routes.

    0 讨论(0)
提交回复
热议问题