将django组合成基于外键的组

时间:2012-02-18 23:54:26

标签: django django-forms

我有一个简单的InventoryItems和Categories设置。我有一个InventoryItems的formset,但想要根据FK类别拆分项目,我不需要或不需要内联表单集。

我所拥有的简化版

class Category(models.Model):
    name = models.CharField(max_length=255)
    inventory = models.BooleanField(default=False)

class Inventory(models.Model):
    name = models.CharField(max_length=255)
    quantity = models.IntegerField()
    category = models.ForeignKey(Category)

def viewOfForm(request):
    categories = Category.objects.filter(inventory=True)
    InventoryFormset = modelformset_factory(Inventory, can_delete=True, extra=1)
    formset = InventoryFormset(request.POST or None, queryset=Inventory.objects.filter(category__inventory=True))
    return render_to_response('template.html', locals())

我想在模板中做什么

{% for category in categories %}
<fieldset class="collapse">
<h2>{{ category.name }}</h2>
{% for form in formset %}
{% if form.category == category %}
{{ form }}
{% endif %}
{% endfor %}
</fieldset>
{% endfor %}

1 个答案:

答案 0 :(得分:3)

您只需要进行一些小改动即可实现这一目标;在form.instance.category模板标记中使用if

{% if form.instance.category == category %}