[英]403 Forbidden Error When Editing a Form - Javascript and Django
[英]“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.