【问题标题】:Failed CSRF token verification in Mezzanine with captcha form使用验证码表单在夹层中的 CSRF 令牌验证失败
【发布时间】: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


    【解决方案1】:

    您必须确保:

    视图函数使用RequestContext作为模板,而不是Context

    但你使用:

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

    并且,从documentationrender_to_response

    默认情况下,模板将使用Context 实例(填充字典中的值)呈现。如果您需要使用上下文处理器,请改为使用 RequestContext 实例呈现模板。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-31
      • 2016-09-09
      • 1970-01-01
      • 1970-01-01
      • 2011-09-25
      • 2012-05-16
      • 2020-03-05
      • 2014-01-09
      相关资源
      最近更新 更多