就学生/年级而言,我提出了解决办法,在这种解决办法中,学生是不可调试的田地,能够按要求加以编辑和更新。 部分内容与本
我将学生的科目和年级的表格结合起来。 py using zip function.
def grade_edit(request, id):
student = student.objects.get(id=id)
grades = grades.objects.filter(studentId=id)
gradeformset = GradeFormSet(request.POST or None)
if request.POST:
gradeformset = GradeFormSet(request.POST, request.FILES, instance=student)
if gradeformset.is_valid():
gradeformset.save()
grades = grades.objects.filter(studentId=id)
return render(request, grade_details.html , { student : student, grades : grades})
else:
gradeformset = GradeFormSet(instance=student)
grades = grades.objects.filter(studentId=id)
zips = zip(grades, gradeformset)
return render(request, grade_edit.html , { zips : zips, student : student, gradeformset : gradeformset })
我的模板看着这样的情况。
<table>
<tr>
{% for field in gradeformset.forms.0 %}
{% if not field.is_hidden %}
<th>{{ field.label }}</th>
{% endif %}
{% endfor %}
</tr>
{% for f in gradeformset.management_form %}
{{ f }}
{% endfor %}
{% for student, gradeform in zips %}
<tr>
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
<td> {{ student.name }} </td>
<td> {{ gradeform.gradeA }} </td>
<td> {{ gradeform.gradeB }} </td>
</tr>
{% endfor %}
</table>
You can read more about Django formset here
http://whoisnicoleharris.com/2015/01/06/implementing-django-formsets.html