如何解决Method "POST" not allowed 405

How to solve Method "POST" not allowed 405

我正在为 API 使用 Django Rest Framework,我遇到了这个问题。在 views.py 中,我的 class 继承自 ModelViewSet,但由于某些原因它不允许发出 POST 请求。对于前端,我使用 React JS 并从那里发出 POST 请求。最后我收到这样的错误:POST http://127.0.0.1:8000/api/software/3/ 405 (Method Not Allowed).

这里是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
        )

这是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

这个错误是因为urlhttp://127.0.0.1:8000/api/software/3/正在调用retrieve方法,这个方法必须通过GET调用。

http://127.0.0.1:8000/api/software/3/ ,好像是一个数据的明细,只能用 PUT 或者 补丁详细,不允许POST方法