Issue with POST Method Returning 405 on ModelViewSet #9627
-
Description: I'm experiencing an issue with a ModelViewSet in Django REST Framework. When I attempt to make a POST request to the registered URL, I receive the following error: 405 Method Not Allowed. However, the POST method is properly defined in my ViewSet. And I had another ViewSets that works fine. I don't understand why this one doesn't work, They are practically same. Below are the details of my setup:
Here is my code: class LaboratoryViewSet(viewsets.ModelViewSet):
queryset = Laboratory.objects.all()
serializer_class = LaboratorySerializer
permission_classes = [IsAuthenticated]
def create(self, request, *args, **kwargs):
print("POST method called") # Debugging
return super().create(request, *args, **kwargs) My Router router = DefaultRouter()
router.register('lab', LaboratoryViewSet, basename='laboratory')
urlpatterns = [
path('api/pharmacies/', include(router.urls)),
] Troubleshooting Permissions: Temporarily removed all permissions to ensure they weren't blocking the request. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
I don't see a problem with what you provided. Which URL is your request calling? You said the method but not the host/path Do other HTTP verbs work? If yes, which ones? GET or OPTION might give you a clue... Have you tried browsing to the API root view? That might give you more information about what endpoints are available. |
Beta Was this translation helpful? Give feedback.
Thank you for your help!
I’ve identified the issue. In my DefaultRouter, I had registered a ViewSet with an empty prefix
('')
before other more specific routes like'lab/'
.I had something like that:
The problem was resolved by simply moving the registration of the ViewSet with the empty prefix
('')
to the end of the router configuration.Thanks again for pointing me in the right direction!