django訪問頁面報(bào)錯(cuò):
Forbidden(403)
CSRF verification failed. Request aborted.
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 whenDjango's CSRF mechanismhas not been used correctly. For POST forms, you need to ensure:
Your browser is accepting cookies.
The view function passes arequestto 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 usingCsrfViewMiddleware, 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.
根據(jù)報(bào)錯(cuò)提示渤弛,依次檢查:
1)django項(xiàng)目settings.py
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',#確認(rèn)存在
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
2〉html中的form添加模板標(biāo)簽{% csrf_token %}
[html]view plaincopy
{%?csrf_token?%} ?
3〉django項(xiàng)目views.py
from?django.shortcuts?import?render_to_response??
from?django.template?import?RequestContext??
def?some_view(request):??
#?...??
? ??return?render(request,'login.html',{'uf':uf}) #不要使用?render_to_response瘩欺,使用render