【问题标题】:How to solve Method "POST" not allowed 405如何解决方法“POST”不允许 405
【发布时间】:2021-06-18 14:40:24
【问题描述】:

我正在使用 Django Rest Framework for API,我遇到了这个问题。在views.py 中,我的类继承自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

【问题讨论】:

  • 你需要使用PUTPATCH
  • PUT 不起作用,抛出错误:PUT 127.0.0.1:8000/api/software/3 400 (Bad Request)
  • PATCH 工作,感谢您的帮助!

标签: python django django-rest-framework django-rest-viewsets


【解决方案1】:

http://127.0.0.1:8000/api/software/3/ ,它看起来像一个数据的细节,细节只能使用PUTPatch,没有POST方法是允许的。

【讨论】:

  • PUT 不起作用,抛出错误:PUT 127.0.0.1:8000/api/software/3 400 (Bad Request)
  • PUT 不起作用可能只是因为您没有提供完整的数据进行更新,PUT 是完全更新操作,而 PATCH 是部分更新操作。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2014-05-23
    • 2018-12-20
    • 2015-11-16
    • 2016-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-07
    • 2016-12-04
    相关资源
    最近更新 更多