[英]How to make Django 2.1 to accept PATCH/DELETE requests
I am building an app with Django 2.1 and I want to be able to do PATCH/DELETE requests through ajax calls. 我正在使用Django 2.1构建应用程序,并且希望能够通过ajax调用来执行PATCH / DELETE请求。 Through researching about this I found out the solution to be to deceive the browser by using a POST request, but setting the header X_METHODOVERRIDE to the desired method.
通过对此进行研究,我发现解决方案是使用POST请求欺骗浏览器,但是将标头X_METHODOVERRIDE设置为所需的方法。
I would start doing this by creating a middleware that will take care of this. 我将通过创建一个可以解决此问题的中间件来开始这样做。 What is the best way of doing?
最好的方法是什么?
Please note that I don't want to use Django-REST 请注意,我不想使用Django-REST
Code so far for making the DELETE request: 到目前为止发出DELETE请求的代码:
view.py view.py
class CategoryManageView(StaffRequiredMixin, View):
model = Category
response_dict = {'status': False, 'text': '', 'data': {}}
def delete(self, request, *args, **kwargs):
cat = get_object_or_404(Category, request.POST['id'])
self.response_dict['data'] = cat
cat.delete()
self.response_dict['status'] = True
self.response_dict['text'] = 'Category deleted successfuly'
return JsonResponse(self.response_dict)
If the ajax call method is set to DELETE instead of POST or GET I get error in console: 如果ajax调用方法设置为DELETE而不是POST或GET,则在控制台中出现错误:
DELETE http://127.0.0.1:8000/dashboard/admin/categories/manage 403 (Forbidden)
删除http://127.0.0.1:8000/dashboard/admin/categories/manage 403(禁止)
The error code 403 indicates that this is because of CSRF protection. 错误代码403表示这是由于CSRF保护引起的。 As the CSRF documentation shows, PUT and DELETE - as well as POST - are considered "unsafe" methods, and Django therefore disallows the requests if they don't have a valid CSRF token.
如CSRF文档所示,PUT和DELETE-以及POST-被视为“不安全”方法,因此Django如果请求没有有效的CSRF令牌,则将拒绝这些请求。
The same page has documentation on how to enable the token in your Ajax requests. 该页面上还包含有关如何在Ajax请求中启用令牌的文档。 Alternatively - although this is strongly discouraged - you can use the
@csrf_exempt
decorator on the view to disable the protection. 另外,尽管强烈建议不
@csrf_exempt
,但是您可以在视图上使用@csrf_exempt
装饰器以禁用保护。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.