我正在努力寻找可能非常基本的东西:我需要为我的大学数据库应用程序生成带有标记的表单。每个模块中的每个学生都有一个获得“性能”的类,该类存储模块的所有标记。有不同的评估,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