【发布时间】:2014-11-12 05:50:21
【问题描述】:
我一直在尝试使用 Django CMS Mezzanine 设置验证码表单的测试版本。它显示验证码,但是当我提交表单时出现错误:
禁止 (403)
CSRF 验证失败。请求中止。
帮助
失败原因:
CSRF token missing or incorrect.
一般来说,当存在真正的跨站请求伪造时,或者没有正确使用 Django 的 CSRF 机制时,就会发生这种情况。对于 POST 表单,您需要确保:
Your browser is accepting cookies.
The view function uses RequestContext for the template, instead of Context.
In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL.
If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data.
You're seeing the help section of this page because you have DEBUG = True in your Django settings file. Change that to False, and only the initial error message will be displayed.
You can customize this page using the CSRF_FAILURE_VIEW setting.
行为与 Firefox 和 Chrome 相同(有或没有隐身)。我正在使用 Python 3.4、Django 1.6.7 和 Mezzanine 3.1.0。我尝试通过多种方式解决此问题: 1)我的html模板:
<body>
<h3>Captcha</h3>
<form method="POST">
{% csrf_token %}
<input name="item_text" id="id_new_item" placeholder="Enter item">
<br>
{{ form.captcha }}
<input type="submit" value="Submit">
</form>
</body>
2) 在我的 settings.py 文件中:
TEMPLATE_CONTEXT_PROCESSORS = (
...
"django.core.context_processors.csrf",
)
MIDDLEWARE_CLASSES = (
...
"django.middleware.csrf.CsrfViewMiddleware",
)
3) 在我的 captcha_test.views.py 中:
from django.views.decorators.csrf import csrf_protect
from django.shortcuts import render_to_response
from django.http import HttpResponse
from captcha_test.forms import CaptchaTestForm
@csrf_protect
def captcha_page(request):
if request.POST:
form = CaptchaTestForm(request.post)
if form.is_valid():
human = True
return HttpResponseRedirect('/')
else:
form = CaptchaTestForm()
return render_to_response('captcha.html', locals())
我的 forms.py 文件,如果这有帮助的话:
from django import forms
from captcha.fields import CaptchaField
class CaptchaTestForm(forms.Form):
item_text = forms.CharField()
captcha = CaptchaField()
有什么见解吗?感谢您的帮助!
【问题讨论】:
标签: python django captcha mezzanine