美文网首页
Django前端表单提交报错,禁止访问 (403),CSRF验证

Django前端表单提交报错,禁止访问 (403),CSRF验证

作者: 夜雨_87aa | 来源:发表于2020-06-06 17:54 被阅读0次
image.png

CSRF验证失败. 请求被中断.

## Help

Reason given for failure:

<pre style="padding: 0px; margin: 0px;">    CSRF token missing or incorrect.
    </pre>

In general, this can occur when there is a genuine Cross Site Request Forgery, or when [Django's CSRF mechanism](https://docs.djangoproject.com/en/2.2/ref/csrf/) 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`](https://docs.djangoproject.com/en/dev/topics/templates/#django.template.backends.base.Template.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.
*   The form has a valid CSRF token. After logging in in another browser tab or hitting the back button after a login, you may need to reload the page with the form, because the token is rotated after a login.

You're seeing the help section of this page because you have `DEBUG = True` in your Django settings file. Change that to `False`, and only the initial error message will be displayed.

You can customize this page using the CSRF_FAILURE_VIEW setting.

报上述错误提示,可以按照如下排查解决
1、检查Django版本,如果是2.0以上,需要检查下setting文件下是否有如下配置,如果没有,需要添加

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',
]

2、前端form表单标签里面是否添加{% csrf_token %}标签


image.png

3、后端处理表单提交视图函数是否添加了{% csrf_token %}处理的功能装饰器

from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def user_login(request):
  pass
image.png

相关文章

网友评论

      本文标题:Django前端表单提交报错,禁止访问 (403),CSRF验证

      本文链接:https://www.haomeiwen.com/subject/xfhftktx.html