使用验证码表单在Mezzanine中验证CSRF令牌失败

时间:2014-09-18 02:40:31

标签: python django captcha mezzanine

我一直在尝试使用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()

任何见解?谢谢你的帮助!

1 个答案:

答案 0 :(得分:2)

您必须确保:

  

视图功能使用RequestContext作为模板,而不是Context

但你使用:

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

并且,从documentationrender_to_response

  

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

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