Неуспешна проверка на CSRF токен в мецанин с формуляр captcha

Опитвам се да настроя тестова версия на формуляр за captcha, използвайки Django CMS, Mezzanine. Той показва captcha, но когато изпратя формуляра, получавам грешката:

Забранено (403)

CSRF проверката е неуспешна. Заявката е прекратена.

Помогне

Посочена причина за неуспех:

CSRF token missing or incorrect. 

По принцип това може да се случи, когато има истинско фалшифициране на заявка между сайтове или когато CSRF механизмът на Django не е използван правилно. За 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()

Някакви прозрения? Благодаря за вашата помощ!


person user3597703    schedule 18.09.2014    source източник


Отговори (1)


Трябва да се уверите, че:

Функцията за преглед използва RequestContext за шаблона вместо Context.

Но вие използвате:

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

И от документацията до render_to_response:

По подразбиране шаблонът ще бъде изобразен с екземпляр Context (попълнен със стойности от речника). Ако трябва да използвате контекстни процесори, изобразете шаблона с RequestContext екземпляр вместо това.

Така че добавянето на context_instance=RequestContext(request) трябва да реши проблема.

person Kevin Christopher Henry    schedule 18.09.2014