将多个模型添加到 inlineformset_factory

mnm*_*mly 5 django foreign-keys django-forms

我有一个像下面这样的模型。

class Content(SimpleModel):
    title = models.CharField(max_length=255)
    body = models.TextField()
    slug = models.SlugField(max_length=50)    

    def __unicode__(self):
        return self.title


class MediumStuff(models.Model):
    meta_value = models.TextField()
    meta_key = models.SlugField('Field Name', max_length=50, blank=True)
    content = models.ForeignKey(Content)

    def __unicode__(self):
        return self.slug


class SmallStuff(models.Model):
    text = models.CharField(max_length=60, blank=True, null=True)
    content = models.ForeignKey(Content)
Run Code Online (Sandbox Code Playgroud)

我想要做的是使用 inlineformset_factory()

我参考了Django Documentation,但他们有一个关于如何使用单个外键模型的示例。

ContentFormSet = inlineformset_factory(Content, [MediumStuff, SmallStuff])

也不

ContentFormSet = inlineformset_factory(Content, (MediumStuff, SmallStuff))

没有用。

由于可以向管理员添加多个内联,我相信这是可以做到的:)

您有任何建议/任何资源或提示吗?或者可能告诉我应该在哪里查看管理员如何处理多个内联?

Igo*_*ira 3

只需为每个相关模型创建一个内联:

MediumStuffInline = inlineformset_factory(Content, MediumStuff)

SmallStuffInline = inlineformset_factory(Content, SmallStuff)

看看admin是怎么做的。每个内联都由 [1] 的子类处理InlineModelAdmin。内联本身是在get_formset()方法 [2] 上创建的。

查看有关如何在视图中使用多个表单集的文档 [3][4]

[1] http://code.djangoproject.com/browser/django/trunk/django/contrib/admin/options.py#L228

[2] http://code.djangoproject.com/browser/django/trunk/django/contrib/admin/options.py#L1243

[3] http://docs.djangoproject.com/en/1.2/topics/forms/modelforms/#using-an-inline-formset-in-a-view

[4] http://docs.djangoproject.com/en/1.2/topics/forms/formsets/#using-more-than-one-formset-in-a-view