[Django]-Django: CSRF token missing or incorrect

42👍

You need to pass RequestContext in render_to_response for csrf_token

For this : (views.py)

from django.template import RequestContext

...

return render_to_response('fileupload/upload.html', {'form': c['UploadFileForm']},  RequestContext(request))
# Added RequestContext

This passes the token for csrf to the template.

5👍

It can also happen if you use @cache_page(60 * 15) decorators. If you cache a page with a form containing a CSRF token, you’ll cache the CSRF token of the first user only. So it’s kinda hard to debug sometimes.

More info from Django documentation

If the csrf_token template tag is used by a template (or the get_token
function is called some other way), CsrfViewMiddleware will add a
cookie and a Vary: Cookie header to the response. This means that the
middleware will play well with the cache middleware if it is used as
instructed (UpdateCacheMiddleware goes before all other middleware).

However, if you use cache decorators on individual views, the CSRF
middleware will not yet have been able to set the Vary header or the
CSRF cookie, and the response will be cached without either one. In
this case, on any views that will require a CSRF token to be inserted
you should use the django.views.decorators.csrf.csrf_protect()
decorator first:

from django.views.decorators.cache import cache_page
from django.views.decorators.csrf import csrf_protect

@cache_page(60 * 15)
@csrf_protect
def my_view(request):
    ...
👤varren

2👍

My answer is similar to the @Yugal Jindle’s answer above.

I am using Django 1.10 and I had a similar issue, it worked for me after editing

return render_to_response(param1, param2)

to

return render(request, param1, param2)

P.S. Make sure you have the below line in your MIDDLEWARE variable in the settings.py

'django.middleware.csrf.CsrfViewMiddleware'
👤Mr.A

1👍

For my case, I use AJAX to post data to my views function, then the same error happens, so the easy method to solve it is to change the data from

data:{ 'k':'v' }

To

data:{ 'k':'v' ,addcsrfmiddlewaretoken:'{{ csrf_token }}',}

because we manually add a csrf-token, so it is not missing or incorrect.

Leave a comment