【问题标题】:PATCH Method not allowed不允许使用 PATCH 方法
【发布时间】:2019-07-12 11:04:12
【问题描述】:

我尝试在 Django 中向我的 API 添加 Patch 方法,但总是以“不允许的方法”结尾。

我在 Django Rest Framework 文档中添加了 mixins.UpdateModelMixin,但是它仍然返回相同的错误。我查看并没有找到我需要在哪里放置授权以允许补丁。

这是 urls.py 和 views.py 中与该视图和路径声明相关的代码。

urls.py

schema_view = get_schema_view(
    openapi.Info(
        title="WAF Management Portal API",
        default_version="v1",
        description="REST api for interaction between Frontend and Backend.",
        contact=openapi.Contact(email="soc-dev-automation@bell.ca"),
    ),
    public=True,
    permission_classes=(permissions.AllowAny,),
)

path(
        'action/dothis/', ActionApiView.as_view(), name="action_api_view"
    ),

views.py

class ActionApiView(mixins.UpdateModelMixin, ActionAPIView):
    """
    post:
        add one or more settings to selected policy

    patch:
        modify or more settings to selected policy

    """

    def get_queryset(self):
        return Policy.objects.allowed_to_user(self.request.user)

    def get_serializer(self, *args, **kwargs):
        return SettingsSerializer(*args, **kwargs)

    @swagger_auto_schema()
    def post(self, request):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(data=request.data)

        if serializer.is_valid():
            selected_policies = serializer.get_selected_policies(queryset)

            .....do some data manipulation (included action_id variable)...

            response = {
                ....prepare response
            }

            return redirect("another_view", action_id=action_id)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    @swagger_auto_schema()
    def patch(self, request):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(data=request.data)

        if serializer.is_valid():
            selected_policies = serializer.get_selected_policies(queryset)

            .....do some data manipulation (included action_id variable)...

            response = {
                ....prepare response
            }

            return redirect("another_view", action_id=action_id)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

【问题讨论】:

  • 什么是 ActionAPIView?

标签: python django django-rest-framework


【解决方案1】:

如果 ActionAPIView 继承自 ModelViewSet ,您可能需要将补丁函数重命名为 update 并将您的网址更改为

path(
    'action/dothis/', ActionApiView.as_view({'patch':'update'}), name="action_api_view"
),

【讨论】:

  • 嗨,我试过这个解决方案,它工作正常。非常感谢。
  • @yuki 如果它适合你,你应该接受这个答案
猜你喜欢
  • 2017-08-29
  • 2018-11-12
  • 2017-10-01
  • 2018-10-02
  • 2021-08-27
  • 2017-06-09
  • 2017-09-17
  • 1970-01-01
相关资源
最近更新 更多