关于Django出现CSRF token missing or incorrect.问题解决办法(参考官方文档)

How to use it

To enable CSRF protection for your views, follow these steps:

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

  2. In any template that uses a POST form, use the csrf_token tag insidethe <form> element if the form is for an internal URL, e.g.:

    <form action="." method="post">{% 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.

  3. 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.

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/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值