put方法在RetrieveUpdateDestroyAPI上不起作用查看Django Rest框架Angular

cidc1ykv  于 2022-12-20  发布在  Go
关注(0)|答案(3)|浏览(124)

我正在尝试在djangorest框架中发出一个put请求。我的视图继承自RetrieveUpdateDestroyAPIView类。
我在前端使用角形,在后端使用django休息。
下面是错误:

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

下面是从angular side到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);

该url被Map到django侧:

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

视图类

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

检索更新数据销毁API查看文档:
http://www.django-rest-framework.org/api-guide/generic-views/#updatemodelmixin
RetrieveUpdateDestroyAPIView用于读-写-删除端点以表示单个模型示例。
提供get、put、patch和delete方法处理程序。
扩展:通用API视图、检索模型混合、更新模型混合、销毁模型混合
检索更新销毁API视图源代码:

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)
p1iqtdky

p1iqtdky1#

SearchCityListCreate的URL模式与/city/x/匹配,因此错误的视图正在处理您的请求。
您通过切换顺序解决了这个问题,但更好的解决方法是确保正则表达式使用^$分别标记URL的开头和结尾。

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

yhived7q2#

您可以使用rest_framework类视图来实现它

class country_detail(APIView):
    def get_object(self,pk):
        try:
            return CountryModel.objects.get(pk=pk)
        except CountryModel.DoesNotExist:
            raise 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()`
brjng4g3

brjng4g33#

我需要颠倒城市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

相关问题