當頁面中form使用POST方式向后台提交時,報如下錯誤:
禁止訪問 (403)
CSRF驗證失敗. 請求被中斷.
Help
Reason given for failure:
CSRF token missing or incorrect.
In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure:
- Your browser is accepting cookies.
- The view function passes a
requestto the template'srendermethod.- In the template, there is a
{% csrf_token %}template tag inside each POST form that targets an internal URL.- If you are not using
CsrfViewMiddleware, then you must usecsrf_protecton any views that use thecsrf_tokentemplate tag, as well as those that accept the POST data.- The form has a valid CSRF token. After logging in in another browser tab or hitting the back button after a login, you may need to reload the page with the form, because the token is rotated after a login.
You're seeing the help section of this page because you haveDEBUG = Truein your Django settings file. Change that toFalse, and only the initial error message will be displayed.
You can customize this page using the CSRF_FAILURE_VIEW setting.
在網上查找了很多資料,普遍采用的解決方法是:
-
檢查
settings.py中是否有下面的配置,如沒有加上:
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware', # 確認存在
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
) -
html中的form添加模板標簽{% csrf_token %}
<form action="/saveBlog/" method="post">
{% csrf_token %}
...
</form> -
針對views.py進行修改
from django.shortcuts import render_to_response
from django.template import RequestContext
def some_blog(request):
# ...
return render_to_response('my_template.html',
my_data_dictionary,
context_instance=RequestContext(request))
以上各步都基本照做了。其中針對視圖的修改,因我的寫法與網上不一樣,我的是:
def edit_blog(request):
template = get_template('editBlog.html')
moods = Mood.objects.all()
html = template.render(locals())
``
return HttpResponse(html)
因為官方文檔上說render是render_to_response的shortcut,所以沒有照網站資料上說的去改。於是錯誤總是無法解決。
幾番掙扎之后,終於在Django出錯頁面中自己給出的解決辦法中有一條:The view function passes a request to the template's rendermethod.(即:視圖函數中傳遞 request 給模板的render方法)。
按這個訪求修改后,終於解決問題了!!
def edit_blog(request):
template = get_template('editBlog.html')
moods = Mood.objects.all()
html = template.render(locals(), request) # 把request傳遞給template.render()
``
return HttpResponse(html)
