我正在尝试在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)
3条答案
按热度按时间p1iqtdky1#
SearchCityListCreate
的URL模式与/city/x/
匹配,因此错误的视图正在处理您的请求。您通过切换顺序解决了这个问题,但更好的解决方法是确保正则表达式使用
^
和$
分别标记URL的开头和结尾。yhived7q2#
您可以使用rest_framework类视图来实现它
brjng4g33#
我需要颠倒城市URL的顺序
事实上,带有PK的城市URL从未被采用。
不良:
良好: