Django - CSRF验证失败 [英] Django - CSRF verification failed
问题描述
当尝试从教程中制作一个简单的表单时,我正在收到一个CSRF验证失败的消息。我做了一些研究,实际上是什么CSRF验证,据我所知,为了使用它,你需要其中一个csrf_token标签在你的HTML,但我没有那个
I'm getting a CSRF verification failed message when trying to make a simple form from a tutorial. I did a little research into what CSRF verification actually is, and to my knowledge, in order to use it you need one of those csrf_token tags in your html, but I don't have that
这是我的模板:
<form action="/testapp1/contact/" method="post">
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
相当简单,位于contact.html
Fairly straightforward, located at contact.html
这是我的urlconf:
from django.conf.urls.defaults import *
Here's my urlconf: from django.conf.urls.defaults import *
urlpatterns=patterns('testapp1.views',
(r'^$', 'index'),
(r'^contact/$','contact')
)
应用程序名称为testapp1。当我键入我的url(http:// localhost:8000 / testapp1 / contact)时,我正确地转到表单。然后当我提交表单时,我会收到验证错误。
The app name is testapp1. When I type my url (http://localhost:8000/testapp1/contact), I correctly go to the form. Then when I submit the form, I get the verification error.
尽管我认为这是不相关的,但我的看法是:
Here's my view although I don't think it's relevant:
def contact(request):
if request.method == 'POST': # If the form has been submitted...
form = ContactForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
subject = form.cleaned_data['subject']
message = form.cleaned_data['message']
sender = form.cleaned_data['sender']
cc_myself = form.cleaned_data['cc_myself']
recipients = ['info@example.com']
if cc_myself:
recipients.append(sender)
print 'Sending Mail:'+subject+','+message+','+sender+','+recipients
return HttpResponseRedirect('/thanks/') # Redirect after POST
else:
form = ContactForm() # An unbound form
return render_to_response('contact.html', {
'form': form,
})
推荐答案
1 。在模板中包含 {%csrf_token%}
内的表单标签。
1. include {% csrf_token %}
inside the form tag in the template.
<强> 2 即可。在render_to_response中使用RequestContext
2. use a RequestContext in render_to_response
return render_to_response('contact.html', {'form': form},
context_instance=RequestContext(request))
[更新]
现在我使用 render
而不是 render_to_response
(与较少打字相同的效果):
Nowadays I use render
instead of render_to_response
(same effect with less typing):
return render(request, 'contact.html', {form: form})
这篇关于Django - CSRF验证失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!