gpt4 book ai didi

python - 带有验证码表单的夹层中的 CSRF token 验证失败

转载 作者:行者123 更新时间:2023-11-28 17:39:53 24 4
gpt4 key购买 nike

我一直在尝试使用 Django CMS Mezzanine 设置验证码表单的测试版本。它显示验证码,但是当我提交表单时出现错误:

禁止 (403)

CSRF 验证失败。请求中止。

帮助

失败原因:

CSRF token missing or incorrect. 

一般情况下,当存在真正的Cross Site Request Forgery,或者没有正确使用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()

有什么见解吗?感谢您的帮助!

最佳答案

您必须确保:

The view function uses RequestContext for the template, instead of Context.

但是你使用:

return render_to_response('captcha.html', locals())

并且,来自 documentationrender_to_response:

By default, the template will be rendered with a Context instance (filled with values from dictionary). If you need to use context processors, render the template with a RequestContext instance instead.

因此添加 context_instance=RequestContext(request) 应该可以解决问题。

关于python - 带有验证码表单的夹层中的 CSRF token 验证失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25903336/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com