首页 > 解决方案 > 如何处理 AJAX 中的补丁方法?

问题描述

如何处理来自 AJAX 的补丁方法。我的后端是用 Django rest API 编写的。Im 使用模型视图集。后端视图如下:

class ProductAPI(viewsets.ModelViewSet):
      serializer_class = ProductSerializer
      queryset  = ProductTbl.objects.all()
      
      @action(detail=False, methods=['PATCH'])
      def get_object(self,*args,**kwargs):
          return get_object_or_404(**kwargs)

      def update_product(self,request,pk):
           try:
                 product_obj = self.get_obj(pk=pk)
                 serializer = self.serializer_class(product_obj,data = request.data,
                                              partial = True)
                if serializer.is_valid():
                    serializer.save()
                    return Response({},status = 200)
                return Response(serializer.errors,status = 400)
           except Exception as e:
                return Response({},status = 500)

网址.py

 path('product/edit/<int:pk>/', ProductAPI.as_view({'patch': 'update_product'}), name='update_products'),   

我的ajax代码如下:

    var form = new FormData($("#update_form")[0])
    $.ajax({
    type:"PATCH",
    url : "/product/edit/1",
    data:form,
    success:function(data){

    },
    error:function(data){

   }
})

不过,我收到错误 405.Method not allowed...

标签: djangodjango-rest-frameworkdjango-views

解决方案


推荐阅读