Django에 대한 CSRF token missing or incorrect.문제 해결 방법(공식 문서 참조)

How to use it
To enable CSRF protection for your views, follow these steps:
  • Add the middleware'django.middleware.csrf.CsrfViewMiddleware' to your list ofmiddleware classes, MIDDLEWARE_CLASSES. (It should comebefore any view middleware that assume that CSRF attacks havebeen dealt with.) Alternatively, you can use the decoratorcsrf_protect() on particular viewsyou want to protect (see below).
  • In any template that uses a POST form, use the csrf_token tag insidethe element if the form is for an internal URL, e.g.:
    {% csrf_token %} 
        

    This should not be done for POST forms that target external URLs, sincethat would cause the CSRF token to be leaked, leading to a vulnerability.

  • In the corresponding view functions, ensure that the'django.core.context_processors.csrf' context processor isbeing used. Usually, this can be done in one of two ways:

    1. Use RequestContext, which always uses'django.core.context_processors.csrf' (no matter what yourTEMPLATE_CONTEXT_PROCESSORS setting). If you are usinggeneric views or contrib apps, you are covered already, since theseapps use RequestContext throughout.

    2. Manually import and use the processor to generate the CSRF token andadd it to the template context. e.g.:

      from django.core.context_processors import csrf
      from django.shortcuts import render_to_response
      
      def my_view(request):
          c = {}
          c.update(csrf(request))
          # ... view code here
          return render_to_response("a_template.html", c)
      

      You may want to write your ownrender_to_response() wrapper that takes careof this step for you.


    3. The utility script extras/csrf_migration_helper.py can help to automate thefinding of code and templates that may need these steps. It contains full helpon how to use it.
      인터넷에서는 대부분 앞의 두 가지 방법을 사용하면 문제를 해결할 수 있다고 말하지만, 세 번째 상황은 그래도 주의할 만하다.
      첨부된 공식 문서 주소:https://docs.djangoproject.com/en/dev/ref/contrib/csrf/
  • 좋은 웹페이지 즐겨찾기