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 = form.save() return HttpResponseRedirect("/") else: form = RegistrationForm() return render_to_response("register.html", {'form': form, }, )
Here's my Template:
{% block content %} <h1>Register</h1> <form action="" method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit"> </form> {% endblock %}
The “Invalid or missing CSRF token” message means that your browser couldn't create a secure cookie, or couldn't access that cookie to authorize your login. This can be caused by ad- or script-blocking plugins, but also by the browser itself if it's not allowed to set cookies.
To fetch a CRSF token, the app must send a request header called X-CSRF-Token with the value fetch in this call. The server generates a token, stores it in the user's session table, and sends the value in the X-CSRF-Token HTTP response header.
These days you should be using the render
shortcut function return render(request, 'template.html')
which uses RequestContext
automatically so the advice below is outdated by 8 years.
render
https://docs.djangoproject.com/en/2.2/topics/http/shortcuts/ {% csrf_token %}
template tagMy 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.
https://docs.djangoproject.com/en/dev/ref/contrib/csrf/
Or add the token to your context manually
Just add this to your views
return render_to_response("register.html", {'form': form, }, context_instance = RequestContext(request))
It will work!!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With