[英]How to store Form Data (a Django form) to browser's local storage, using javascript and not Django sessions?
我想通過表單(Django 表單)從用戶那里獲取數據並將其存儲在瀏覽器的本地存儲中,使用 javascript 而不使用 Django 會話。
我的代碼看起來像:
./forms.py :
class digitize(forms.Form):
medicinename = forms.CharField(label='Medicinename', max_length=100)
quantity = forms.CharField(label='Quantity', max_length=100)
./e_commerce.html :
<form id="digitizer_form" role="form" action="/MediciansDigitizer/Presc/" method="post" enctype="multipart/form-data">
{% csrf_token %}
<h3 class="prod_title">Add Detail</h3>
{{iform.as_table}}{{ dform.as_p }}
<div class="">
<button type="Submit" class="btn btn-default btn-lg">Digitize</button>
</div>
</form>
<script>
window.onload = function() {
// Check for LocalStorage support.
if (localStorage) {
// Add an event listener for form submissions
document.getElementById('digitizer_form').addEventListener('submit', function() {
// Get the value of the MedicineName field :
Now, this is where I need help. Here I want to give in the 'MedicineName'
field of the form defined above, So that
I can get the MedicineName entered by the user from the form
and store it in the browser storage.
The logic should look something like this:
// get the value of the MedicineName so that
I can store it in a variable like this:
var Medicine = document.getElementById('MedicineName').value;
//but because I am using a django form, and linking it
in the e_commerce.html template through {%csrf_token%} ,
{{iform.as_table}} and {{ dform.as_p }}
and have not assigned any id ('MedicineName') to any element (as
I didn't create any form element manually inside the html template,
but has made a "form class" in forms.py), I can't follow
this approach and so I am stuck here because I don't know how to
do it the other way round.
// and then Save the variable in localStorage
like this :
localStorage.setItem('Medicine', MedicineName);
});
}
}
</script>
那么,如何在html模板的javascript中使用用戶從Django表單輸入的MedicineName,通過javascript將名稱存儲在瀏覽器的本地存儲中呢?
如果有人能幫我解決這個問題,我將不勝感激。 提前致謝!
您的表單呈現錯誤
<form id="digitizer_form" role="form" action="/MediciansDigitizer/Presc/" method="post" enctype="multipart/form-data">
{% csrf_token %}
<h3 class="prod_title">Add Detail</h3>
{{iform.as_table}}
<div class="">
<button type="Submit" class="btn btn-default btn-lg">Digitize</button>
</div>
</form>
<form id="other_form" role="form" method="post" >
{{ dform.as_p }}
<div class="">
<button type="Submit" class="btn btn-default btn-lg">Digitize</button>
</div>
</form>
這是兩種形式,因此應將它們呈現為兩種不同的形式。 否則你會發現服務器端表單驗證不起作用。 如果您需要一個包含來自兩個 django 表單的字段的 HTML 表單,請讓一個 django 表單擴展另一個。
然后,由於您有一個名為medicinename
的表單元素,該表單將生成一個 id 為id_medicinename
的 HTML 輸入元素,因此您可以訪問它
document.getElementById('id_medicinename').value
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.