繁体   English   中英

以Django形式使用.submit(function)时,“禁止403-CSRF验证失败”

[英]“Forbidden 403 - CSRF verification failed” when using .submit(function) in Django form

我一直在使用Django开发应用程序,该应用程序有很多表格,每个表格都在不同的页面中。 在第一个视图中,我只是问用户一个简单的信息,即POST发送到Python并用于某些公式。 我以前这样做的代码如下所示,并且运行平稳:

<html>
<head>
    <title>Data</title>
</head>

{% load staticfiles %}
<link rel="stylesheet" href="{% static 'app/content/bootstrap.css' %}">
<link rel="stylesheet" href="{% static 'app/content/custom.css' %}">

<script src="{% static 'app/scripts/jquery-1.10.2.min.js' %}"></script>
<script src="{% static 'app/scripts/jquery.validate.js' %}"></script>
<script src="{% static 'app/scripts/jquery.maskedinput.min.js' %}"></script>
<script src="{% static 'app/scripts/custom.js' %}"></script>

{% if error == 404 %}
<label>Who are you? Go away!</label>
<br>
{% endif %}
Welcome! Give me your data!
<body>
    <form action="/search/" method="post" id="myPrettyForm">
        {% csrf_token %}
        <input type="text" name="q" id="q">
        <input type="submit" value="Go!">
    </form>
</body>
<script type="text/javascript">

    $("#q").mask("00000000000");

</script>
</html>

就像我说的那样,这段代码运行良好。 但是,我想添加一个函数,单击“提交”后, q输入字段将被禁用。 为此,我尝试将这段代码添加到上面的脚本中:

$("#myPrettyForm").submit(function () {
    $("#myPrettyForm:input").prop("disabled", true);
});

但是,当我将此代码段添加到代码中时,每次尝试提交表单时,都会收到“ 禁止(403)CSRF验证失败。请求中止。 ”错误。 ,这种错误通常是相关的形式不具有{% csrf_token %}的元素。 但是,我的表单已经包含此元素。

那么,我在这里做错了什么? 并且,如果我使用了错误的方法来防止用户在提交表单后在输入中进行写操作,那么我可以使用其他哪种方法?

request.POST是包含表单数据的字典。 禁用输入类将使包括csrf_token在内的所有输入都被禁用。 正确的方法是通过id引用组件并将组件保持为“只读”,就像您执行$("#fieldId").prop("readonly", true);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM