我正在努力尋找可能非常基本的東西:我需要爲我的大學數據庫應用程序生成帶有標記的表單。每個模塊中的每個學生都有一個獲得「性能」的類,該類存儲模塊的所有標記。有不同的評估,Performance類爲他們計算平均值。在Django模板中動態生成表單的Javascript驗證
我需要能夠進入,例如,所有標記爲第一次評估,而我做了一個動態生成的Django表單爲模板的表:
{% for performance in performances %}
<tr>
<td>
{{ performance.student }}
</td>
<td>
{% if to_mark == 1 %}
<input type="text" class="input-mini" name="{{ student.student_id }}" value="{{ performance.assessment_1 }}">
{% else %}
{{ performance.assessment_1 }}
{% endif %}
</td>
And the same for the other assessments (to_mark gets passed on by views.py to indicate which assessments needs to be marked here)
我失敗了以使用Inlineformfields,因此決定動態生成一個表單並使用Javascript對其進行驗證,這也是因爲驗證很簡單(必須是介於1和100之間的數字),並且還因爲我想使用Javascript來計算動態平均值。
我的問題是,我對Javascript沒有任何線索。所有教程(像這樣的http://www.w3schools.com/js/js_form_validation.asp)的JavaScript函數使用窗體字段的名稱,但在我的情況下,該名稱是動態生成的,這樣我就可以在views.py輕鬆地訪問它:
if student.student_id in request.POST:
tmp = request.POST[student.student_id]
try:
mark = int(tmp)
if mark in range(0, 100):
performance = Performance.objects.get(student=student, module=module)
if to_change == 1:
performance.assessment_1 = mark
...and so on for the other assessments
except ValueError:
pass (in case someone accidentally enters a letter and not a number)
有沒有一種方法可以使用Javascript來解決我的表單字段?還是應該使用與以student_id作爲名稱讀取它不同的方法?我怎麼能這樣做?
感謝, 託比
謝謝 - 我想我必須開始研究一些基本的Javascript,然後......這是非常有用的要知道除了領域的名稱之外還有其他方法。 – Tobi 2013-03-15 09:50:40
JavaScript並不是那麼困難。技巧並不是將數據緊密地耦合到DOM。 – Brandon 2013-03-15 11:03:24