CSRF token validation error in Mezzanine with captcha form
I am trying to set up a test version of a captcha form using Django CMS, Mezzanine. It displays the captcha, but when I submit the form, I get the error:
Forbidden (403)
Failed to check CSRF. The request was aborted.
reference
Rejection reason:
CSRF token missing or incorrect.
In general, this can happen if a genuine cross-site request routine exists, or when the JSR-CGF mechanism is not being used correctly. For POST forms, you need:
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.
The behavior is the same with Firefox and Chrome (with or without incognito). I am using Python 3.4, Django 1.6.7 and Mezzanine 3.1.0. I tried to solve the problem in several ways: 1) My html template:
<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) In my settings.py file:
TEMPLATE_CONTEXT_PROCESSORS = (
...
"django.core.context_processors.csrf",
)
MIDDLEWARE_CLASSES = (
...
"django.middleware.csrf.CsrfViewMiddleware",
)
3) In my captcha_test.views.py file:
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())
My forms.py file, if it helps at all:
from django import forms
from captcha.fields import CaptchaField
class CaptchaTestForm(forms.Form):
item_text = forms.CharField()
captcha = CaptchaField()
Any ideas? Thank you for your help!
source to share
You must make sure that:
The view function uses
RequestContext
for the template instead ofContext
.
But you are using:
return render_to_response('captcha.html', locals())
And from the documentation before render_to_response
:
By default, the template will be rendered with an instance
Context
(filled with values from the dictionary). If you need to use context processors, render the template with an instanceRequestContext
.
So adding context_instance=RequestContext(request)
should solve the problem.
source to share