【发布时间】: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<pk>[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