遇到該問題的情境:在Django中采用Ajax提交表單,涉及到跨域問題,
解決措施:
- 在html頁面中的表單內添加如下代碼:
{% csrf_token %}
- 在視圖函式所在的py檔案中添加如下代碼:
from django.views.decorators.csrf import csrf_exempt
# 如果是FBV,則在接收表單資料的視圖函式上添加@csrf_exempt
@csrf_exempt
def func():
pass
# 如果是CBV,則在類上或者類方法上加方法裝飾器
# 方法一如下,裝飾器name引數指明要裝飾的函式名稱
@method_decorator(csrf_exempt, name="dispatch")
class ClassView(View):
def post(self, request, *args, **kwargs):
pass
# 方法二如下,直接裝飾dispatch方法
class ClassView(View):
@method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
return super(StudentsView, self).dispatch(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
pass
在Django中,可以使用 @csrf_exempt 注解來標識一個視圖可以免除csrf驗證,
該方法原文解釋如下:
Mark a view function as being exempt from the CSRF view protection.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/209586.html
標籤:其他
