當我提交表單,我得到以下錯誤:Django的CSRF令牌丟失或不正確的錯誤403
CSRF verification failed
Reason given for failure:
CSRF token missing or incorrect.
我views.py是:
def name(request):
if request.method == 'POST':
form=NameForm(request.POST)
if form.is_valid():
name=form.cleandata['your_name']
return HttpResponseRedirect('/thanks/',RequestContext(request))
else:
form=NameForm()
return render_to_response('contact.html')
我setting.py文件:
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
我的forms.py文件是:
class NameForm(forms.Form):
your_name=forms.CharField(initial='your name',max_length=100)
我contact.html是:
<form action="/your-name/" method="POST">
{% csrf_token %}
{{form}}
<input type="submit" value="Submit" />
</form>
urls.py是:
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^search/$', search),url(r'^contact/$',contact),
url(r'^name/$',name),url(r'^your-name',name),url(r'^thanks/$',thank)
]
'返回選擇render_to_response( 'contact.html',{ '形式':形式},context_instance = RequestContext的(請求))'添加這一行insted的的'返回選擇render_to_response( 'contact.html')' –
我對django瞭解不多,但csrf的基本思想是存儲在會話中的值,然後發送到表單以在提交時對其進行評估。 即檢出您的會話設置,並確保它工作正常。 – SaidbakR
render_to_response中的context_instance參數在Django 1.8中已被棄用,並在Django 1.10中被刪除。當使用獲取錯誤:render_to_response()得到了一個意外的關鍵字參數'context_instance' – Tango