首页 文章

django内联表单集,具有嵌套表单的复杂模型

提问于
浏览
1

假设我的django模型看起来像这样:

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

class OrderLine(models.Model):
 # One or more lines per order
 order = models.ForeginKey(Order)
 common_line = models.OneToOneField(CommonLine)

class CommonLine(models.Model):
 # common elements of what might be on a line item...
 taxes = model...
 amount = model...

我想创建一个使用inlineformset的表单来编辑每个订单的一个或多个行(OrderLine和CommonLine) .

我可以创建一个与Order和OrderLine一起使用的formset - 但是如何在显示formset时让内联formset为我提供CommonLine类中的所有详细项目 . 似乎内联表单集的文档要求内联表单 - 订单上的多行只能映射到单个类...

我没有看到文档中的内容吗?我敢肯定我可以覆盖一些东西,我只是不确定在哪里 .

谢谢你的帮助...

3 回答

  • 1

    需要进行一些细微的修改才能使Nathan的代码在Django 1.3中工作http://yergler.net/blog/2009/09/27/nested-formsets-with-django/ . 下面的行导致ManagementForm错误 .

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

    使用modelformset_factory并手动定义查询集似乎可行,但我还没有实现添加额外功能 .

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

    我还必须手动将数据传递给is_valid方法中的子子表单:

    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
    

    编辑:

    可以使用jQuery创建新实例 . 见this question

  • 0

    我用http://yergler.net/blog/2009/09/27/nested-formsets-with-django/解决了问题 . 请求在forms.py文件中使用以下更正:

    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,
    

    刚刚开始使用Django 1.4.1 .

  • 2

    这听起来非常类似于在帮助中谈到的方法http://yergler.net/blog/2009/09/27/nested-formsets-with-django/内森写道他如何照顾"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."

    还可以在这里找到更多解释Django Forms Newbie Question

相关问题