55👍
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.
36👍
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)
- [Django]-How to use subquery in django?
- [Django]-Django create userprofile if does not exist
- [Django]-Django Rest Framework Conditional Field on Serializer
14👍
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)
- [Django]-Why does django ORM's `save` method not return the saved object?
- [Django]-Django Rest Framework – Could not resolve URL for hyperlinked relationship using view name "user-detail"
- [Django]-AttributeError: 'module' object has no attribute 'tests'
5👍
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.
- [Django]-In django do models have a default timestamp field?
- [Django]-Use variable as dictionary key in Django template
- [Django]-Django equivalent of SQL not in
1👍
For anyone using ExtendedSimpleRouter
in rest_framework_extensions
, the accepted solution needs a small modification. The self.trailling_slash
has to be after the super().__init__()
like this.
from rest_framework_extensions.routers import ExtendedSimpleRouter
class OptionalSlashRouter(ExtendedSimpleRouter):
def __init__(self):
super(ExtendedSimpleRouter, self).__init__()
self.trailing_slash = "/?"
- [Django]-How to import csv data into django models
- [Django]-How to resolve "django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: foo" in Django 1.7?
- [Django]-Django returning HTTP 301?
1👍
For the DefaultRouter
class, it’s the same as Ryan Allen’s answer:
from rest_framework.routers import DefaultRouter
class OptionalSlashRouter(DefaultRouter):
"""Make all trailing slashes optional in the URLs used by the viewsets
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.trailing_slash = '/?'
router = OptionalSlashRouter()
...
- [Django]-Django – makemigrations – No changes detected
- [Django]-Location of Django logs and errors
- [Django]-Update all models at once in Django