Django提交表单报错-CSRF token missing or incorrect.

时间:2022-07-25 19:29:49

日志建议解决办法:
In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django’s CSRF mechanism has not been used correctly. For POST forms, you need to ensure:

  • Your browser is accepting cookies.
  • The view function passes a request to the template’s render method.
  • In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL.
  • If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data.

第一确定setting文件中是或否存在django.middleware.csrf.CsrfViewMiddleware

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',#确定是否存在或者注销
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

第二在表单中添加 {% csrf_token %}

 <form action="/home" method="post" enctype="multipart/form-data">
{# 添加以下语句 #}
{% csrf_token %}
<p>
<input type="file" value="file">
<input type="submit" value="提交">
</p>
</form>

更多内容访问个人站点:www.gaocaishun.cn