我一直在關注這篇有用的文章http://collingrady.wordpress.com/2008/02/18/editing-multiple-objects-in-django-with-newforms/。不幸的是,他不提示模板代碼,所以我在那裏猜測。TemplateSyntaxError在通過填充表單上的forloop迭代時收到DoesNotExist
我想在頁面中創建一堆表單,將多個對象添加到模型中,並使用由頁面變量或頁面頂部的另一個表單設置的一些常用屬性。這是給老師的標示。
我views.py:
def record_assessments(request, teachinggroup, objective):
theclass = TeachingGroup.objects.get(name__iexact = teachinggroup)
pupils = Pupil.objects.filter(teaching_group = theclass)
theobjective = Objective.objects.get(code = objective)
thedate = datetime.date.today()
if request.method == 'POST':
aforms = [PupilAssessmentForm(request.POST, prefix=x.id, instance=Assessment()) for x in pupils]
if all(af.is_valid() for af in aforms):
for af in aforms:
new_record = af.save(commit = False)
new_record.objective = theobjective
new_record.date = thedate
new_record.save()
return redirect("/app/" + theclass + "/" + marksheet + "/" + theobjective.strand.code|lower + "/")
else:
aforms = [PupilAssessmentForm(prefix=str(x.id)) for x in pupils]
return render_to_response('recordassessments.html', locals())
我沒有設法檢查邏輯在第一循環,如果還沒有,因爲我還沒有成功地將窗體正常呢。
頁面呈現,如果正確,我把
else:
aforms = [PupilAssessmentForm(prefix=str(x.id), instance=x) for x in pupils]
但後來我追平從評估模型的ModelForm於光瞳模型中的對象,這似乎是錯誤的。
我的模板:
{% for af in aforms %}
<form action="" method="post">
{{af.instance}}{{ af.errors }}
<p>
{{ af }}
{% endfor %}
<input type="submit" value="Submit">
</form>
錯誤(選擇片段):
Exception Type: TemplateSyntaxError
Exception Value: Caught DoesNotExist while rendering:
error at line 20
Caught DoesNotExist while rendering:
20 {% for af in aforms %}
然而在aforms列表會出現在頁面變量:
aforms
[<two.app.forms.PupilAssessmentForm object at 0x21db0d0>,
<two.app.forms.PupilAssessmentForm object at 0x21db650>]
這是一篇很老的文章,可能在[formsets](https://docs.djangoproject.com/en/1.3/topics/forms/modelforms/#model-formsets)可用之前編寫。你應該使用這些。 –
謝謝,我玩過,但我不認爲formset可以做我想做的事。除非我非常愚蠢,這是可能的。我想遍歷學生,獲得先前的評估數據,以便在鄰近表格單元格中顯示,然後呈現單個表單字段,爲該學生添加記錄,或者在存在的情況下更新記錄。對於我來說,表單集對於全新對象(直接表單集)或對正在更新的模型(modelformsets)中的對象進行迭代。是否可以遍歷一個模型(瞳孔),但在另一個(評估)中添加/更新記錄? – nimasmi