使用DRF框架进行接口测试时,出现“method \PUT\(或\\DELETE\) not allowed!”,经过多方搜索,
问题分析见:
最终发现无外乎以下操作可以尝试解决:
REST_FRAMEWORK = {'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.DjangoModelPermissions',),'DEFAULT_AUTHENTICATION_CLASSES': ('rest_framework.authentication.SessionAuthentication','rest_framework.authentication.TokenAuthentication',)
class RiskView(ModelViewSet):#响应器renderer_classes = [JSONRenderer,BrowsableAPIRenderer]# 分页器=自己写的分页类,不能=列表pagination_class = CustomPagination#指定查询表queryset = Risk.objects.all()# 指定序列化器serializer_class = RiskSerializerhttp_method_names = ['put','get','delete','post']
此时路径需要如下设置,不然会报下面四的问题:
path(r'risks/', views.RiskView.as_view({'get':'list','post':'create'})),path(r'risks/detail//',views.RiskView.as_view({'get': 'retrieve','delete':'destroy','put': 'update'})),
/api/resource/
/api/resource/1/
path(r'risks/', views.RiskView.as_view({'get':'list','post':'create'})),path(r'risks/detail//',views.RiskView.as_view({'get': 'retrieve','delete':'destroy','put': 'update'})),
1.默认的viewset和默认的router,但发送put、delete请求提示不支持
官方实现update方法的时候要求传入pk,所以在put时将请求URL改成:path/pk/就可以了。
2.使用put和delete请求方式,结果返回正常,但数据修改未生效
先访问/api-auth/login/登录django,然再操作就可以修改数据了
参考链接:
https://stackoverflow.com/questions/43529555/how-to-not-allow-the-put-method-at-all-but-allow-patch-in-a-drf-viewset
https://blog.csdn.net/qq_39402334/article/details/83409691
https://www.cnblogs.com/wurijie/p/13339859.html