【问题标题】:put method not working on RetrieveUpdateDestroyAPIView Django Rest Framework Angularput 方法在 RetrieveUpdateDestroyAPIView Django Rest Framework Angular 上不起作用
【发布时间】:2018-03-01 18:40:20
【问题描述】:

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

我在前端使用 angular django rest 在后端。

这里是错误:

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)

【问题讨论】:

  • 也许您的 URL 模式有冲突,并且请求没有被 SearchCityDetail 处理。
  • @Alasdair 这是个好主意,我会调查一下
  • @Alasdair 所以这两个 url 模式的位置与现在相反。我遇到了连接被拒绝的问题,但我会解决这个问题,我认为我们可能会很好url(r'city/(?P&lt;pk&gt;[0-9]+)/$',SearchCityDetail.as_view()) # detele put get url url(r'city', SearchCityListCreate.as_view()), # create city list url
  • @Alasdair 我爱你。成功了

标签: django django-rest-framework put http-error django-generic-views


【解决方案1】:

SearchCityListCreate 的 URL 模式与 /city/x/ 匹配,因此您的请求被错误的视图处理。

您通过切换顺序解决了这个问题,但更好的解决方法是确保您的正则表达式有 ^$ 分别标记 URL 的开头和结尾。

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

【讨论】:

  • 谢谢@Alasdair 我现在就做这些改变
【解决方案2】:

您可以使用 rest_framework 类视图 `class country_detail(APIView) 来实现它: def get_object(self,pk): 尝试: 返回 CountryModel.objects.get(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】:

    我需要颠倒我的城市网址的顺序

    就这样,带有 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-08
      • 2023-04-09
      • 2019-05-18
      • 2021-07-30
      • 2020-07-30
      • 2013-09-07
      • 2019-09-15
      • 1970-01-01
      相关资源
      最近更新 更多