简体   繁体   English

将多个模型添加到inlineformset_factory

[英]Adding Multiple Models to inlineformset_factory

I have a model like below. 我有一个如下的模型。

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)

What I wanna do is to create formset for content that has inline forms for models of MediumStuff and SmallStuff using inlineformset_factory() 我想做的是使用inlineformset_factory()创建具有用于MediumStuff和SmallStuff模型的内联表单的内容的formset

I referred to Django Documentation , but they have a example of how to work with single foreign key model. 我提到了Django文档 ,但他们有一个如何使用单个外键模型的示例。

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

nor 也不

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

didn't work. 没用。

Since it is possible to add multiple inlines to admin, I believe this can be done :) 既然可以为管理员添加多个内联,我相信这可以做到:)

Do you have any suggestion / any resources or tips? 您有任何建议/任何资源或提示吗? Or possibly tell me where I should look at to see how admin handles multiple inlines? 或者可能告诉我应该在哪里查看管理员如何处理多个内联?

Just create one inline for each related model: 只需为每个相关模型创建一个内联:

MediumStuffInline = inlineformset_factory(Content, MediumStuff)

SmallStuffInline = inlineformset_factory(Content, SmallStuff)

Take a look how admin does. 看看管理员是怎么做的。 Each inline is handled by a subclass of InlineModelAdmin [1]. 每个内联由InlineModelAdmin [1]的子类处理。 The inline itself is created on the get_formset() method [2]. 内联本身是在get_formset()方法[2]上创建的。

Check out the documentation on how to use more that one formset in a view [3][4] 查看有关如何在视图中使用更多一个formset的文档[3] [4]

[1] http://code.djangoproject.com/browser/django/trunk/django/contrib/admin/options.py#L228 [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 [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 [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 [4] http://docs.djangoproject.com/en/1.2/topics/forms/formsets/#using-more-than-one-formset-in-a-view

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM