django inline formsets with a complex model for the nested form

前端 未结 3 731
没有蜡笔的小新
没有蜡笔的小新 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:07

    This sounds very similar to the approach talked about at help http://yergler.net/blog/2009/09/27/nested-formsets-with-django/ where Nathan writes about how he catered for "a multi-level data model; an example of this kind of model would be modeling City Blocks, where each Block has one or more Buildings, and each Building has one or more Tenants."

    Some more explanations can aslo be found here Django Forms Newbie Question

    0 讨论(0)
  • 2020-12-18 17:08

    I solved problem with http://yergler.net/blog/2009/09/27/nested-formsets-with-django/. Pleas use the following correction in forms.py file:

            instance=None
                pk_value = hash(form.prefix)
    
    +       correct_data = None
    +       if (self.data):
    +           correct_data = self.data;
            # store the formset in the .nested property
            form.nested = [
    -           TenantFormset(data=self.data,
    +           TenantFormset(data=correct_data,
                                instance = instance,
    

    Just working on Django 1.4.1 very well.

    0 讨论(0)
  • 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:

    0 讨论(0)
提交回复
热议问题