如何将InlineFormSet放入Django中的ModelFormSet?

时间:2009-12-05 15:28:38

标签: django django-models django-forms

我希望通过ModelFormSet显示多个表单,其中每个表单依次为InlineFormSets显示连接到该对象的所有对象。

现在我不确定如何为每个ModelFormSet提供实例。我考虑过继承BaseModelFormSet,但我不知道从哪里开始,并且想知道在我遇到所有麻烦之前这是否可行。

提前致谢!

2 个答案:

答案 0 :(得分:2)

我发现了一篇专注于确切问题的文章。它工作正常!

http://yergler.net/blog/2009/09/27/nested-formsets-with-django/

为了完整起见,我复制了代码片段:

class Block(models.Model):
    description = models.CharField(max_length=255)

class Building(models.Model):
    block = models.ForeignKey(Block)
    address = models.CharField(max_length=255)

class Tenant(models.Model):
    building = models.ForeignKey(Building)
    name = models.CharField(max_length=255)
    unit = models.CharField(max_length=255)

form django.forms.models import inlineformset_factory, BaseInlineFormSet

TenantFormset = inlineformset_factory(models.Building, models.Tenant, extra=1)

class BaseBuildingFormset(BaseInlineFormSet): 

    def add_fields(self, form, index):
        # allow the super class to create the fields as usual
        super(BaseBuildingFormset, self).add_fields(form, index)

        # created the nested formset
        try:
            instance = self.get_queryset()[index]
            pk_value = instance.pk
        except IndexError:
            instance=None
            pk_value = hash(form.prefix)

        # store the formset in the .nested property
        form.nested = [
            TenantFormset(data=self.data,
                            instance = instance,
                            prefix = 'TENANTS_%s' % pk_value)]

BuildingFormset = inlineformset_factory(models.Block, models.Building, formset=BaseBuildingFormset, extra=1)

答案 1 :(得分:0)

正如jnns所说,你想使用inlineformset_factory