我正在尝试在 django Rest 框架中发出 put 请求。我的 View 继承自 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())
View 类
class SearchCityDetail(RetrieveUpdateDestroyAPIView):
queryset = SearchCity.objects.all()
serializer_class = SearchCitySerializer
RetrieveUPdateDestoryAPIView 文档:
http://www.django-rest-framework.org/api-guide/generic-views/#updatemodelmixin
检索更新销毁APIView 用于读写删除端点来表示单个模型实例。
提供 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)
最佳答案
您的 SearchCityListCreate
的 URL 模式与 /city/x/
匹配,因此您的请求正在由错误的 View 处理。
您通过切换顺序解决了该问题,但更好的解决方法是确保您的正则表达式具有 ^
和 $
分别标记 URL 的开头和结尾.
url(r'^city$', SearchCityListCreate.as_view()),
url(r'^city/(?P<pk>[0-9]+)$',SearchCityDetail.as_view()),
关于django - put 方法不适用于 RetrieveUpdateDestroyAPIView Django Rest Framework Angular,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49056546/