代码之家  ›  专栏  ›  技术社区  ›  amazing carrot soup

put方法不适用于RetrieveUpdatedStroyapiView Django Rest框架Angular

  •  2
  • amazing carrot soup  · 技术社区  · 8 年前

    我试图在django rest框架中发出put请求。我的视图继承自RetrieveUpdatedStroyapiView类。

    我在前端使用角形支架,在后端使用django支架。

    以下是错误:

    Failed to load resource: the server responded with a status of 405 (Method Not Allowed)
    ERROR 
    detail:"Method "PUT" not allowed."
    

    下面是从angular侧到django rest的put请求的完整实现

    editcity(index){
        this.oldcityname = this.cities[index].city;
         const payload = {
          citypk: this.cities[index].pk,
          cityname: this.editcityform.form.value.editcityinput
        };
         this.suitsettingsservice.editcity(payload, payload.citypk)
           .subscribe(
             (req: any)=>{
               this.cities[index].city = req.city;
               this.editcitysucess = true;
               // will have changed
               this.newcityname = this.cities[index].city;
             }
           );
      }
    

    正在调用的服务

    editcity(body, pk){
        const url = suitsettingscity + '/' + pk;
        return this.http.put(url, body);
    

    映射到django端的url:

    url(r'^city/(?P<pk>[0-9]+)',SearchCityDetail.as_view())
    

    视图类

    class SearchCityDetail(RetrieveUpdateDestroyAPIView):
        queryset = SearchCity.objects.all()
        serializer_class = SearchCitySerializer
    

    RetrieveUPdateDestoryAPIView文档:

    http://www.django-rest-framework.org/api-guide/generic-views/#updatemodelmixin

    RetrieveUpdateDestroyAPIView 用于读写删除端点以表示单个模型实例。

    提供get、put、patch和delete方法处理程序。

    扩展:GenericAPIView、RetrieveModelMixin、UpdateModelMixin、DestroyModelMixin

    RetrieveUpdateDestroyAPIView源代码:

    class RetrieveUpdateDestroyAPIView(mixins.RetrieveModelMixin,
                                       mixins.UpdateModelMixin,
                                       mixins.DestroyModelMixin,
                                       GenericAPIView):
        """
        Concrete view for retrieving, updating or deleting a model instance.
        """
        def get(self, request, *args, **kwargs):
            return self.retrieve(request, *args, **kwargs)
    
        def put(self, request, *args, **kwargs):
            return self.update(request, *args, **kwargs)
    
        def patch(self, request, *args, **kwargs):
            return self.partial_update(request, *args, **kwargs)
    
        def delete(self, request, *args, **kwargs):
            return self.destroy(request, *args, **kwargs)
    
    3 回复  |  直到 8 年前
        1
  •  3
  •   Alasdair    8 年前

    您的URL模式 SearchCityListCreate 正在匹配 /city/x/ 所以你的请求被错误的视图处理了。

    您通过切换顺序修复了该问题,但更好的修复方法是确保您的正则表达式 ^ $ 分别标记URL的开始和结束。

    url(r'^city$', SearchCityListCreate.as_view()),
    url(r'^city/(?P<pk>[0-9]+)$',SearchCityDetail.as_view()),
    
        2
  •  1
  •   Sanjeev kumar    7 年前

    您可以使用rest\u框架类视图` class country\u detail(APIView)'来实现它: def get\u对象(self,pk): 尝试: 返回CountryModel。物体。获取(pk=pk) CountryModel除外。DoesNotExist公司: 升起Http404

    def get(self,request,pk,format=None):
        country=self.get_object(pk)
        serializer=CountrySerializer(country)
        return Response(serializer.data,status=status.HTTP_200_OK)
    def put(self,request,pk,format=None):
        country=self.get_object(pk)
        serializer=CountrySerializer(country,data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data,status=status.HTTP_200_OK)
        return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)
    def delete(self,request,pk,format=None):
        country=self.get_object(pk)
        country.delete()` 
    
        3
  •  0
  •   amazing carrot soup    8 年前

    我需要颠倒城市URL的顺序

    事实上,带有pk的城市url从未被使用过。

    错误:

    url(r'city', SearchCityListCreate.as_view()), # create city list url
    url(r'city/(?P<pk>[0-9]+)/$',SearchCityDetail.as_view()), 
    

    好的:

     url(r'city/(?P<pk>[0-9]+)/$',SearchCityDetail.as_view()), 
     url(r'city', SearchCityListCreate.as_view()), # create city list url