Forbidden (403)
CSRF verification failed. Request aborted.
今天遇到这个问题,在https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ref-contrib-csrf 上解决办法:
-
Add the middleware 'django.middleware.csrf.CsrfViewMiddleware' to your list of middleware classes, MIDDLEWARE_CLASSES. (It should come before any view middleware that assume that CSRF attacks have been dealt with.)
Alternatively, you can use the decorator csrf_protect() on particular views you want to protect (see below).
-
In any template that uses a POST form, use the csrf_token tag inside the <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, since that would cause the CSRF token to be leaked, leading to a vulnerability.
发现setting.py文件里已经有'django.middleware.csrf.CsrfViewMiddleware',
然后在HTML文件的<FORM>标签后加上{% csrf_token %}问题依然没有解决。
最后在网上找到答案,说要在MIDDLEWARE_CLASSES.里加上'django.middleware.csrf.CsrfResponseMiddleware'。
继续测试,问题解决,把HTML文件的<FORM>标签后去掉{% csrf_token %}不再报错。注释掉MIDDLEWARE_CLASSES 里的'django.middleware.csrf.CsrfViewMiddleware'也不报错。
转载于:https://blog.51cto.com/frocs/696815