I'm using Django Rest Framework for API and I faced this problem. In views.py
my class inherits from ModelViewSet
, but for some reason it doesn't allow making a POST
request. For frontend I'm using React JS and I make a POST request from there. And in the end I'm getting an error like this: POST http://127.0.0.1:8000/api/software/3/ 405 (Method Not Allowed)
.
Here's views.py
:
from rest_framework.viewsets import ModelViewSet
from .serializers import (
CategorySerializer,
SoftwareSerializer,
SoftwareListRetrieveSerializer,
CategoryDetailSerializer,
CustomPaginatorSerializer
)
from ..models import Category, Software
class CategoryViewSet(ModelViewSet):
queryset = Category.objects.all()
serializer_class = CategorySerializer
pagination_class = None
action_to_serializer = {
"retrieve": CategoryDetailSerializer,
}
def get_serializer_class(self):
return self.action_to_serializer.get(
self.action,
self.serializer_class
)
class SoftwareViewSet(ModelViewSet):
queryset = Software.objects.all()
serializer_class = SoftwareSerializer
pagination_class = CustomPaginatorSerializer
action_to_serializer = {
"list": SoftwareListRetrieveSerializer,
"retrieve": SoftwareListRetrieveSerializer
}
def get_serializer_class(self):
return self.action_to_serializer.get(
self.action,
self.serializer_class
)
Here's urls.py
:
from rest_framework import routers
from .views import CategoryViewSet, SoftwareViewSet
router = routers.SimpleRouter()
router.register('category', CategoryViewSet, basename='category')
router.register('software', SoftwareViewSet, basename='software')
urlpatterns = []
urlpatterns += router.urls
http://127.0.0.1:8000/api/software/3/ , it looks like a detail of a data, you can only use PUT or Patch in details, no POST method is allowed.