【发布时间】:2013-03-14 18:39:33
【问题描述】:
我正在为可能非常基本的事情而苦苦挣扎:我需要为我的大学数据库应用程序生成一个带有标记的表单。每个模块中的每个学生都有一个班级,其中存储了该模块的所有分数。有不同的评估,Performance 类计算它们的平均值。
例如,我需要能够输入第一次评估的所有分数,并且我使用动态生成的 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 django django-forms