arooo arooo - 2 years ago 201
Python Question

CSRF Token missing or incorrect

Beginner at Django here, I've been trying to fix this for a long time now.
I do have 'django.middleware.csrf.CsrfViewMiddleware' in my middleware classes and I do have the token in my post form.

Heres my code, what am I doing wrong?

from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from chartsey.authentication.forms import RegistrationForm
from django.template import RequestContext
from django.core.context_processors import csrf

def register(request):

if request.method == 'POST':
c = RequestContext(request.POST, {})
form = RegistrationForm(c)
if form.is_valid():
new_user =
return HttpResponseRedirect("/")
form = RegistrationForm()

return render_to_response("register.html", {'form': form, }, )

Here's my Template:

{% block content %}

<form action="" method="POST"> {% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit">

{% endblock %}

Answer Source

My guess is that you have the tag in the template but it's not rendering anything (or did you mean you confirmed in the actual HTML that a CSRF token is being generated?)

Either use RequestContext instead of a dictionary

render_to_response("foo.html", RequestContext(request, {}))

Or make sure you have django.core.context_processors.csrf in your CONTEXT_PROCESSORS setting.

Or add the token to your context manually

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download