django 使用mixins时报HTTP方法patch method not allow

具体报错文本

"detail":"Method \"PUT\" not allowed."

花了一晚上才知道的原因,初学mixins打算用UpdateModelMixin实现更新功能的,在postman用patch对服务传数据,服务端一直报method not allow。

刚开始的思路是服务端没有写put方法导致,后来写了个put方法,仍然报错,看了一下源码的dipatchdjango 使用mixins时报HTTP方法patch method not allowdjango 使用mixins时报HTTP方法patch method not allow

发现这里的method是有的,怎么会报错呢,因为配置路由的时候用的是router.register这个被restful封装了的方法,所以我就改成django原来的urlpattern,这个时候按照CBV的路由编辑方式[类名].as_view(),终端立马就报错了。django 使用mixins时报HTTP方法patch method not allow

接着又看了as_view的源码,发现了原来问题发生在这里django 使用mixins时报HTTP方法patch method not allow

发现这里说as_view()被重写了,这里的action绑定了http method,意思就是在as_view()里面要用k-v的形式写明http method对应了那个类方法,然后他才会调用这个类方法。

我改了路由django 使用mixins时报HTTP方法patch method not allow

就可以行得通了,这里as_view()的源码没有看透彻,但就是通过这个把http method对应到了UpdateModelView的update。