CSRF Token missing or incorrect CSRF Token missing or incorrect python python

CSRF Token missing or incorrect


Update: This answer is from 2011. CSRF is easy today.

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.

  1. Use render https://docs.djangoproject.com/en/2.2/topics/http/shortcuts/
  2. Add CSRF middleware https://docs.djangoproject.com/en/2.2/ref/csrf/
  3. Use the {% csrf_token %} template tag
  4. Confirm you see the CSRF token value being generated, AND submitted in your form request

Original Response

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.

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!!


Try using render instead of render_to_response:

from django.shortcuts import renderrender(request, "foo.html", {})

Django - what is the difference between render(), render_to_response() and direct_to_template()?

As stated in the link above it was introduced in Django 1.3 and automatically uses RequestContext