Django:inlineformsets

时间:2015-12-08 10:32:18

标签: python django

我正在尝试将内联添加到我的django表单中。用户可以在“网站”中创建“网站”。表格用户可以创建多功能的员工'到那个'网站'。

我已经遵循了一个我认为是解决方案的教程,但无法让它发挥作用。

目前我收到错误:

  

'调用modelformset_factory而不定义'字段'或者'排除'明确禁止。'

这是我的尝试。

models.py

class Site(models.Model):
    ...

class Staff(models.Model):
    site = models.ForeignKey(Site)
    ....

views.py

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

        form.nested = self.nested_formset_class(
            instance=form.instance,
            data=form.data if self.is_bound else None,
            prefix=' %s-%s' % (
                form.prefix,
                self.nested_formset_class.get_default_prefix(),
            ),
        )

    def is_valid(self):
        result = super(BaseNestedFormset, self).is_valid()
        if self.is_bound:
            # look at any nested formsets, as well
            for form in self.forms:
                result = result and form.nested.is_valid()

        return result

    def save(self, commit=True):
        result = super(BaseNestedFormset, self).save(commit=commit)
        for form in self:
            form.nested.save(commit=commit)

        return result


def nested_formset_factory(site_model, staff_model):
    parent_child = inlineformset_factory(
        site_model,
        staff_model,
        formset=BaseNestedFormset,
    )

    parent_child.nested_formset_class = inlineformset_factory(
        staff_model,
    )

    return parent_child


class SiteCreate(CreateView):
    model = Site
    form_class = SiteForm
    queryset = Site.objects.all()
    success_url = '/site/list'

    def get_form_class(self):
        return nested_formset_factory(
            Site,
            Staff,
        )

forms.py

class SiteForm(forms.ModelForm):
    class Meta:
        model = Site
        exclude = ('creation', 'last_modified')

1 个答案:

答案 0 :(得分:1)

def nested_formset_factory(site_model, staff_model):
    parent_child = inlineformset_factory(
        site_model,
        staff_model,
        formset=BaseNestedFormset,
        fields = ('one', 'two', 'ect')
    )