How to put InlineFormSet in ModelFormSet in Django?

I would like to display several forms through ModelFormSet, where each of the forms displays alternately InlineFormSetsfor all objects associated with the object.

Now I'm not sure how to provide instances for each ModelFormSet. I was thinking about subclassification BaseModelFormSet, but I don’t know where to start, and I would like to know if this is possible at all before I overcome all the problems.

Thanks in advance!

+3
source share
2 answers

I found an article that focuses on the exact issue. It works great!

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

For completeness, I copied the code snippets:

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)
+2

Source: https://habr.com/ru/post/1724819/


All Articles