I want to associate a REST API end point to two urls, "manager" and "manager/". So I added two path entries in the urlpatterns with these urls. But it seems something that can be handled with some kind of configuration. Is there such a configuration with django?
thanks

Dani AI

Generated

Short answer: yes — avoid duplicating two patterns and pick a canonical URL plus one of these approaches to handle the other form. was right to look at redirects, but the behavior is implemented by Django’s CommonMiddleware together with the APPEND_SLASH setting: if only manager/ exists and APPEND_SLASH=True, a request for manager will be redirected to manager/. (docs.djangoproject.com)

To accept both forms without any redirect, use a regex URL that allows an optional trailing slash. Example with re_path:

from django.urls import re_path

re_path(r'^manager/?$', views.manager_view, name='manager')

That pattern matches .../manager and .../manager/ in-place (no redirect). Use this when the endpoint must accept both forms literally. (docs.djangoproject.com)

If the endpoint is provided by Django REST Framework, prefer configuring the router rather than duplicating routes. Routers default to trailing slashes; to remove them:

from rest_framework.routers import DefaultRouter

router = DefaultRouter(trailing_slash=False)
router.register(r'manager', ManagerViewSet, basename='manager')

To make DRF-generated routes accept an optional slash globally, subclass and set trailing_slash = '/?' after super().__init__(). (django-rest-framework.org)

Caveats and best practice: don’t forget that APPEND_SLASH redirects can break non-GET requests — in DEBUG Django will raise a helpful error for POST/PUT/DELETE/PATCH when the slash is missing, and in production a redirect can drop POST data. For APIs it’s usually cleaner to pick one canonical style (commonly no trailing slash for JSON APIs) and make the server or router enforce a single canonical URL. (docs.djangoproject.com)

I admit I won't answer this directly but let's figure out first what happens with and without the forward slash. I'll defer to
https://www.thoughtco.com/urls-ending-with-slash-3466509

OK, that's a good clue how you might handle this. Since no slash forces a redirect, that's my clue to see how Django redirects. For that you have to scour your Django docs. Like this one: https://docs.djangoproject.com/en/2.0/ref/contrib/redirects/
Read until it sinks in. To me that's where your magic has to happen.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.