Reputation: 3
I'm pretty new to Django Rest Framework and I've been investigating this issue but can't find any solution. I'm pretty sure it will be a small detail but I'm out of idea.
I'm using DRF for a project. The team made the choice to not end URL paths with a ' / '. I have an endpoint linked to an APIView with a POST method. We want to do some stuff with a body sent in this POST. However calling it brings (Postman response):
405 Method Not allowed
{
"detail": "Method \"POST\" not allowed."
}
Putting a ' / ' at the end of the URL path works (Postman response for normal behavior):
{
"success": True,
"message": "A message returned by the function in APIView"
}
urls.py
from django.urls import path, include
from runbook import views
from rest_framework.routers import DefaultRouter
router = DefaultRouter(trailing_slash=False)
router.register(r'my_objects', views.ObjectViewset)
urlpatterns = [
path('', include(router.urls)),
path('my_objects/myFunction',
views.MyFunctionView.as_view(),
name="my-function")
views.py
class MyFunctionView(APIView):
"""
"""
def post(self, request, format=None):
try:
MyObject.objects.get(slug=slugify(request.data['candidate_name']))
except MyObject.DoesNotExist:
return Response(boolean_response(False))
else:
return Response(boolean_response(True))
What I read and tried:
I also tried to:
Is it possible to make this request without '/'? Am I using Django tools wrong? Is there any subtlety I am not seeing ? So if anyone has a solution, advice or idea. Thank you !
Upvotes: 0
Views: 1096
Reputation: 3
So as said by @Arakkal Abu in the comment the router conflict with the other path in urlpatterns
Solution: send the router include at the end of the urlpatterns
router = DefaultRouter(trailing_slash=False)
router.register(r'my_objects', views.ObjectViewset)
urlpatterns = [
path('my_objects/myFunction',
views.MyFunctionView.as_view(),
name="my-function"),
path('', include(router.urls))
]
Indeed my_objects/myFunction is considered as part of the route my_objects/ where my_objects/myFunction/ is considered as a separate route and that's why it was working.
Upvotes: 0