Django实用技巧--处理delete和put请求

最近使用restful风格去写api的时候,发现当我调用post和get方法是没问题的,但是当我调用delete方法就会出现错误:

Method Not Allowed (DELET):

经过半天折腾,发现是ajax的请求参数写错了,现做出以下总结

1.ajax中

$.ajax({
   url: '/user/3',
   type: 'delete',   # 千万别写错,
   data: {'name': 'name', },
   dataType: 'json',
   async: false,
   success: function (data) {
       console.log(data);
   }
})

2.在视图类中,由于Django对于PUT/DELETE请求并没有像POST/GET那样有一个字典结构。我们需要手动处理request.body获取参数

from django.http import QueryDict

class UserView(View):

    def get(self, request):
		pass
		
    def delete(self, request):
        DELETE = QueryDict(request.body)
        name = DELETE.get('name')
        print(name)
        return JsonResponse({'code': 200, 'msg': 'success'}, safe=False)

参考博客:
https://blog.csdn.net/weixin_33832340/article/details/87108866
https://blog.csdn.net/yyy72999/article/details/83987625

你可能感兴趣的:(django)