不允许使用PATCH方法

时间:2019-07-12 11:04:12

标签: python django django-rest-framework

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

我添加了Django Rest Framework文档中提到的mixins.UpdateModelMixin,但是,它仍然返回相同的错误。我看了一下,但没有找到允许授权Patch的位置。

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

1 个答案:

答案 0 :(得分:0)

如果ActionAPIView是从ModelViewSet继承的,则可能需要将补丁函数重命名为update并将URL更改为

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