django inline formsets with a complex model for the nested form

前端 未结 3 735
没有蜡笔的小新
没有蜡笔的小新 2020-12-18 16:36

Say I have django model that looks something like this:

class Order(models.Model):
 number = models...
 date = models...

class OrderLine(models.Model):
 # O         


        
3条回答
  •  悲&欢浪女
    2020-12-18 17:19

    Some minor changes were needed to make Nathan's code at http://yergler.net/blog/2009/09/27/nested-formsets-with-django/ work in Django 1.3. The line below causes a ManagementForm Error.

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

    Usings the modelformset_factory and manually defining the queryset seems to work, but I have not implemented the ability to add extras.

    TenantFormset = modelformset_factory(models.Tenant, extra=0)
    
    form.nested = [
            TenantFormset(
                            queryset = Tenant.objects.filter(building = pk_value),
                            prefix = 'value_%s' % pk_value
                            )
                        ]
    

    I also had to manually pass data to the sub-sub-forms in the is_valid method:

    def is_valid(self):
    result = super(BaseProtocolEventFormSet, self).is_valid()
    
    for form in self.forms:
        if hasattr(form, 'nested'):
            for n in form.nested:
                n.data = form.data
                if form.is_bound:
                    n.is_bound = True
                for nform in n:
                    nform.data = form.data
                    if form.is_bound:
                        nform.is_bound = True
                # make sure each nested formset is valid as well
                result = result and n.is_valid()
    return result
    

    EDIT:

    New instances can be created using jQuery. See this question:

提交回复
热议问题