django_Forbidden (CSRF token missing or incorrect.):_views无法正常返回结果

9 篇文章 0 订阅
1 篇文章 0 订阅

问题描述:

 写了个静态页面,可以正常访问,然后在静态页面加了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>

 

感谢以下大大:参考:

https://blog.csdn.net/up1012/article/details/81032368

https://www.guhei.net/forum.php?mod=viewthread&tid=1449&extra=page%3D1%26filter%3Dtypeid%26typeid%3D38

https://www.cnblogs.com/iwangzheng/p/3777043.html

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值