removing trailing slashes in django rest framework in all urls: added with router, manually or using include

Viewed 1777

I'm building an API using Django REST frameworks and would like to get rid of all the trailing slashes in all the urls. I did add APPEND_SLASH = False in settings.py

Here are the different cases I encountered:

  1. Explicit urls: No problem since we can control the regex fully:

urlpatterns = [...,url(r'^api/objects/(?P<pk>[0-9]+)/property$', SomeView.as_view(), name='object-property'),...]

Which allows to send requests to /api/objects/1/property

  1. Using a router:

router = routers.DefaultRouter(trailing_slash=False)

router.register(r'some-endpoint',SomeViewSet,base_name='some_endpoint')

url(r'^api/', include(router.urls)),

Which allows to send requests to /api/some-endpoint

  1. Problem: Using third-party packages

For instance I'm trying to use django-rest-auth. I have installed it with pip and, following the docs I added the urls I need (including registration) to urlpatterns like so:

url(r'^api/', include('rest_auth.urls')), url(r'^api/registration/account-confirm-email/(?P<key>[-:\w]+)/$', ConfirmEmailView.as_view(), name='account_confirm_email'), url(r'^api/registration/', include('rest_auth.registration.urls')),

this will make, for instance, the endpoint /api/login/ active but WITH a trailing slash which I don't want for consistency.

I then tried to remove url(r'^api/', include('rest_auth.urls')) and, focusing on the login endpoint, imported its view:

from rest_auth.views import LoginView

and added the url to urlpatterns hoping to be able to use it without the trailing slash:

url(r'^api/login$', LoginView.as_view(), name='rest_login'),

or

url(r'^api/login', LoginView.as_view(), name='rest_login'),

None of these worked.

However if I add the trailing slash: url(r'^api/login/$', LoginView.as_view(), name='rest_login')

the endpoint will work.

  1. Minor Problem: For the admin site

I have a similar issue with the admin site which is added with:

url(r'^admin/', admin.site.urls),

all the endpoints have trailing_slashes including /admin/

while: url(r'^api/docs', include_docs_urls(title='API Doc',public=False))

will add the docs without any trailing slashes anywhere.

So how can I remove the trailing slashes for: - django-rest-auth or any other third party package? - for the admin website?

Thanks a lot for your help.

0 Answers
Related