使对象在django formsets中可迭代

时间:2011-02-22 08:59:59

标签: python django-forms

以下是我的观点:

def manage(request):
    qs = Author.objects.none()
    AuthorFormSet = modelformset_factory(Author)
    if request.method == 'POST':
        formset = AuthorFormSet(request.POST, request.FILES)
        if formset.is_valid():
            formset.save()
            return HttpResponseRedirect('/frm/thanks/')
    else:
        formset = AuthorFormSet(queryset=qs)

    return render_to_response("manage.html", {
        "formset": formset
    })

def thanks(request):
    return render_to_response("thanks.html")

html模板:

<html>
<body>
<form method="post">
    {{ formset.management_form }}
    {% for form in formset %}
    {{ form.id }}
    <ul>
        <li>{{ form.name }}</li>
        <li>{{ form.title }}</li>
        <li>{{ form.birth_date }}</li>
     </ul>
    {% endfor %}
<p><input type="submit" value="Send message" /></p>
</form>
</body>
</html>

当我访问表单时,会出现此错误:Caught TypeError while rendering: 'AuthorFormFormSet' object is not iterable

那么如何在django formsets下使对象可迭代?

2 个答案:

答案 0 :(得分:2)

这是一个令人耳目一新的老问题,但我发现了

{% for form in formset.form %}
    {{ form }}
{% endfor %}

只会渲染一个没有标签的表单。 IMO正确渲染应该是这样的:

{% for form in formset.forms %}
    {{ form }}
{% endfor %}
  • notice .forms而不是.form

答案 1 :(得分:0)

这对我有用:

{% for form in formset.form %}