我正在开发 Django 1.4.2 版。我已经实现了这个简单的表单示例(灵感来自 djangobook):
# views.py
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.core.mail import send_mail
from mysite.contact.forms import ContactForm
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(request, 'contact_form.html', {'form': form})
# 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 }}
{% csrf_token %}
</table>
<input type="submit" value="Submit">
</form>
</body>
</html>
# forms.py
from django import forms
class ContactForm(forms.Form):
subject = forms.CharField()
email = forms.EmailField(required=False)
message = forms.CharField()
对于我尝试过的所有浏览器(chrome、maxthon、firefox),一切正常,但在 IE9 中,我收到 HTTP 403 被拒绝。
关于是什么原因的任何线索?
编辑:经过更深入的调查,我发现问题出在:当询问空表单时,导航器收到 csrf cookie,但由于未知原因,它在发布表单时没有发回这个 cookie。这个问题似乎只有当 cookie 来自 pythonanywhere.com 的 nginx 服务器时才会出现,当我从我自己的 apache 服务器进行测试时,cookie 被发送回去。
以下是从服务器捕获的两个标头:
HTTP/1.1 200 OK
Server: nginx/1.2.5
Date: Wed, 21 Nov 2012 13:56:31 GMT
Content-Type: text/html; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
Vary: Cookie
Set-Cookie: csrftoken=1AJjzkbUgJdKAmkbiHicJ3or2Mfi6AbD; expires=Wed, 20-Nov-2013 13:56:31 GMT; Max-Age=31449600; Path=/
HTTP/1.1 200 OK
Date: Wed, 21 Nov 2012 13:56:50 GMT
Server: Apache/2.2.15 (CentOS)
Vary: Cookie
Set-Cookie: csrftoken=2iMZSH1s0vJnEt4tRRY7FciT1Q7orrVF; expires=Wed, 20-Nov-2013 13:56:50 GMT; Max-Age=31449600; Path=/
Keep-Alive: timeout=180, max=100
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: text/html; charset=utf-8
唯一显着的区别似乎是来自 apache 的 Kee-Alive 标头......
你认为它可以来自那里吗?