Django: CSRF token missing or incorrect

前端 未结 3 2045
广开言路
广开言路 2020-11-29 08:26

The error is at location http://127.0.0.1:8000/fileupload/form.py

I have version 1.3 of django. I have tried specifying localhost:8000 as stated in someone else\'s q

3条回答
  •  无人及你
    2020-11-29 08:52

    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):
        ...
    

提交回复
热议问题