Django 1.4中的CSRF保护
我正在尝试通过阅读 The Django Book来学习django,但CSRF保护存在问题。我在这里找到了很多建议,但似乎对我没有用。
I am trying to learn django by working through "The Django Book", and I'm having a problem with CSRF protection. I've found lots of suggestions here, but none seem to work for me.
使用Chrome浏览器,我收到消息: CSRF令牌丢失或不正确
。
使用Internet Explorer,我收到消息:未设置CSRF cookie
。
Using Chrome I get the message: CSRF token missing or incorrect
.
Using Internet Explorer I get the message: CSRF cookie not set
.
如果我在settings.py中将'django.middleware.csrf.CsrfViewMiddleware'
注释掉,一切似乎都可以正常工作(尽管没有任何邮件被邮寄到假地址)。尝试在我的视图上放置一个 csrf_protect
装饰器,但这没有帮助。我还尝试注释掉对 send_mail
的调用,但我仍然遇到CSRF失败,因此显然是ContactForm引起了问题。
If I comment out 'django.middleware.csrf.CsrfViewMiddleware'
in settings.py, everything seems to work (although nothing gets mailed to the phony address of course.) I've tried putting a csrf_protect
decorator on my view, but it doesn't help. I've also tried commenting out the call to send_mail
, and I still get a CSRF failure, so apparently it's the ContactForm which is causing the problem.
(我正在使用django 1.4.1)
(I'm using django 1.4.1.)
我需要做什么?
from django.shortcuts import render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from contact.forms import ContactForm
from django.template import RequestContext
from django.core.mail import send_mail
def contact(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
send_mail(
cd['subject'],
cd['message'],
cd.get('email', 'noreply@example.com'),
['siteowner@example.com'],
)
return HttpResponseRedirect('/contact/thanks/')
else:
form = ContactForm()
return render_to_response('contact_form.html', {'form': form}, context_instance=RequestContext(request))
def thanks(request):
return HttpResponse("Thanks for the feedback")
forms.py
from django import forms
class ContactForm(forms.Form):
subject = forms.CharField()
email = forms.EmailField(required=False)
message = forms.CharField()
contact_form.html
<html>
<head>
<title>Contact us</title>
</head>
<body>
<h1>Contact us</h1>
{% if form.errors %}
<p style="color: red;">
Please correct the error{{ form.errors|pluralize }} below.
</p>
{% endif %}
<form action="" method="post">
<table>
{{ form.as_table }}
</table>
<input type="submit" value="Submit">
</form>
</body>
</html>
如果要csrf保护,请在 {%csrf_token%}
标记。
If you want csrf protection, put the {% csrf_token %}
tag in your form.
如果您不想使用csrf保护,请导入并放入 @csrf_exempt 装饰器(请参见文档)。
If you don't want csrf protection, import and put the @csrf_exempt
decorator at the top of your view (see the docs).