Python Django - CSRF 验证失败
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4547639/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Django - CSRF verification failed
提问by JPC
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
尝试从教程中制作简单表单时,我收到 CSRF 验证失败消息。我对 CSRF 验证实际上是什么做了一些研究,据我所知,为了使用它,您需要在 html 中使用这些 csrf_token 标签之一,但我没有
Here's my template:
这是我的模板:
<form action="/testapp1/contact/" method="post">
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
Fairly straightforward, located at contact.html
相当简单,位于contact.html
Here's my urlconf: from django.conf.urls.defaults import *
这是我的 urlconf: from django.conf.urls.defaults import *
urlpatterns=patterns('testapp1.views',
(r'^$', 'index'),
(r'^contact/$','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.
应用程序名称是 testapp1。当我输入我的 url (http://localhost:8000/testapp1/contact) 时,我正确地转到了表单。然后当我提交表单时,我收到验证错误。
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 = ['[email protected]']
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,
})
采纳答案by Paulo Scardine
The fix
修复
1. include {% csrf_token %}insidethe form tag in the template.
1. 包含{% csrf_token %}在模板中的表单标签内。
2. if for any reason you are using render_to_responseon Django 1.3 and above replace it with the renderfunction. Replace this:
2. 如果出于任何原因您render_to_response在 Django 1.3 及更高版本上使用,请将其替换为renderfunction。替换这个:
# Don't use this on Django 1.3 and above
return render_to_response('contact.html', {'form': form})
With this:
有了这个:
return render(request, 'contact.html', {form: form})
The renderfunction was introduced in Django version 1.3- if you are using an ancient version like 1.2 or belowyou must use render_to_responsewith a a RequestContext:
该render函数是在 Django 1.3 版中引入的- 如果您使用的是 1.2 或以下的古老版本,则必须render_to_response与 aa 一起使用 RequestContext:
# Deprecated since version 2.0
return render_to_response('contact.html', {'form': form},
context_instance=RequestContext(request))
What is CSRF protection and why would I want it?
什么是 CSRF 保护,我为什么需要它?
It is an attack where an enemy can force your users to do nasty things like transferring funds, changing their email address, and so forth:
在这种攻击中,敌人可以迫使您的用户做一些令人讨厌的事情,例如转移资金、更改他们的电子邮件地址等:
Cross-Site Request Forgery (CSRF) is an attack that forces an end user to execute unwanted actions on a web application in which they're currently authenticated. CSRF attacks specifically target state-changing requests, not theft of data, since the attacker has no way to see the response to the forged request. With a little help of social engineering (such as sending a link via email or chat), an attacker may trick the users of a web application into executing actions of the attacker's choosing. If the victim is a normal user, a successful CSRF attack can force the user to perform state changing requests like transferring funds, changing their email address, and so forth. If the victim is an administrative account, CSRF can compromise the entire web application. Source: The Open Web Application Security Project
跨站点请求伪造 (CSRF) 是一种攻击,它强制最终用户在当前已通过身份验证的 Web 应用程序上执行不需要的操作。CSRF 攻击专门针对改变状态的请求,而不是窃取数据,因为攻击者无法看到对伪造请求的响应。借助社会工程学的一点帮助(例如通过电子邮件或聊天发送链接),攻击者可能会诱使 Web 应用程序的用户执行攻击者选择的操作。如果受害者是普通用户,成功的 CSRF 攻击可以迫使用户执行状态更改请求,例如转移资金、更改他们的电子邮件地址等。如果受害者是管理帐户,CSRF 可以危害整个 Web 应用程序。来源:开放式 Web 应用程序安全项目
Even if you don't care about this kind of thing now the application may grow so the best practice is to keep CSRF protection on.
即使你现在不关心这种事情,应用程序可能会增长,所以最好的做法是保持 CSRF 保护。
Should not CSRF protection be optional?
CSRF 保护不应该是可选的吗?
It is optional but turned on by default (the CSRF middleware is included by default). You can turn it off:
它是可选的,但默认开启(默认包含 CSRF 中间件)。你可以关闭它:
- for a particular view by decorating it with the
csrf_excemptdecorator. - for every view by removing the CSRF middleware from the middleware list at
settings.py
- 通过使用装饰
csrf_excempt器装饰特定视图。 - 通过从中间件列表中删除 CSRF 中间件,为每个视图
settings.py
If you turn it off system-wide you can turn it on for a particular view by decorating it with the csrf_protectdecorator.
如果您在系统范围内关闭它,您可以通过用装饰csrf_protect器装饰它来为特定视图打开它。
回答by b1_
For Django 1.4
对于姜戈 1.4
settings.py
设置.py
MIDDLEWARE_CLASSES = (
...
'django.middleware.csrf.CsrfViewMiddleware',
)
view.py
查看.py
from django.template.defaulttags import csrf_token
from django.shortcuts import render
@csrf_token
def home(request):
"""home page"""
return render(request,
'template.html',
{}
)
template.html
模板.html
<form action="">
{% csrf_token %}
....
</form>
回答by hustljian
views.py:
视图.py:
from django.shortcuts import render_to_response
from django.template import RequestContext
def my_view(request):
return render_to_response('mytemplate.html', context_instance=RequestContext(request))
mytemlate.html:
我的模板.html:
<form action="/someurls/" method="POST">{% csrf_token %}

