问题描述:
写了个静态页面,可以正常访问,然后在静态页面加了form表单,输入用户名,密码,在views中获取并打印,点击提交时就报错403,特此再次补充下,之前写过一篇相同的问题。
后台报错:
Forbidden (CSRF token missing or incorrect.): /index/
前端报错:
Forbidden (403)
CSRF verification failed. Request aborted.
Help
Reason given for failure:
CSRF token missing or incorrect.
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.
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.
原因分析:
django的默认配置中设置了跨站请求的限制,并将其禁止的状态,form表单在提交时,除了常用的字段之外,额外添加一个token ,这个token是服务器端生成的,是一个随机的数字。服务器端就会检查从浏览器发过来的数据中有没有token,并且这个token的值是不是和服务器端保存的相等,如果相等,就继续执行操作,如果不相等,那这次POST请求肯定是伪造的。
解决方案:
方案一:将settints中对于跨站请求的限制注掉,风险在于那些通过基于受信任的输入form和对特定行为无需授权的已认证的用户来执行某些行为的web应用。已经通过被保存在用户浏览器中的cookie进行认证的用户将在完全无知的情况下发送HTTP请求到那个信任他的站点,进而进行用户不愿做的行为。
方案二:在需要提交的form表单中加上如下代码
{% csrf_token %}
我的完整的static代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
{# <h1 style="background-color: antiquewhite;color: black">用户输入</h1>#}
<form action="/index/" method="post">
{% csrf_token %} <!--加入这行 -->
用户名:<input type="text" name="username"><br/>
密码: <input type="password" name="password"><br/>
<input type="submit" value="提交">
</form>
<script src="/static/js/jquery-1.11.0.min.js"></script>>
</body>
</html>
感谢以下大大:参考: