在填充的表单列表中迭代for循环时捕获的TemplateSyntaxError不存在

时间:2011-09-02 12:53:54

标签: django django-templates django-forms

我一直在关注这篇有用的文章http://collingrady.wordpress.com/2008/02/18/editing-multiple-objects-in-django-with-newforms/。不幸的是他并没有暗示模板代码,所以我猜它在那里。

我想在页面中创建一堆表单,将多个对象添加到模型中,其中一些常见属性由页面变量或页面顶部的另一个表单设置。这是教师的标记。

我的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())

我还没有设法检查第一个if循环中的逻辑,因为我还没有设法正确地发布表单。

如果我放

,页面会正确呈现
    else:
        aforms = [PupilAssessmentForm(prefix=str(x.id), instance=x) for x in pupils]

然后我将一个ModelForm从评估模型绑定到Pupil模型中的一个对象,这似乎是错误的。

我的模板:

{% 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>]

2 个答案:

答案 0 :(得分:0)

奇怪的是,django不应该在渲染django模型时抛出DoesNotExist ......但是......你正在渲染一个表单。我的建议是在您的视图代码中检查结果,以确保您在学生和其他查询集中获得结果。

答案 1 :(得分:0)

我不知道为什么,但我设法通过将列表更改为字典来完成它,无论如何这都符合我的需要,将表单显示为每个学生的表行以及其他一些评估数据。对于任何知道替代方法的人来说,我原来的问题仍然是开放的,这种方法可以更直接地解决我最初提出的问题,但这是我如何做到的:

views.py(相关位):

    if request.method == 'POST':
        assessment_grid = {}
        for x in pupils:
            form = PupilAssessmentForm(request.POST, prefix=str(x.id))
            try:
                assessment = Assessment.objects.filter(objective = theobjective).filter(pupil = x).filter(date__lte = thedate).latest('date')
            except Assessment.DoesNotExist:
                assessment = None
            pupil_row = [assessment, form]
            assessment_grid[x] = pupil_row
        if all(pupil_row[1].is_valid() for pupil, pupil_row in assessment_grid.items()):
            for pupil, pupil_row in assessment_grid.items():
                new_record = pupil_row[1].save(commit = False)
                new_record.objective = theobjective
                new_record.date = thedate
                new_record.teacher = theclass.teacher
                new_record.pupil = pupil
                new_record.save()
            return redirect("some link")
     else:
        assessment_grid = {}
        for x in pupils:
            form = PupilAssessmentForm(prefix=str(x.id))
            try:
                assessment = Assessment.objects.filter(objective = theobjective).filter(pupil = x).filter(date__lte = thedate).latest('date')
            except Assessment.DoesNotExist:
                assessment = None
            pupil_row = [assessment, form]
            assessment_grid[x] = pupil_row
    return render_to_response('recordassessments.html', locals())

我不确定是否有一种更优雅的方式来组装字典,因为我不是特别干。我不知道为什么我可以解压缩包含表单而不是列表的字典。我的语法错了吗?无论如何:问题排序;页面渲染。