我有一组看起来像这样的模型:
class Page(models.Model): title = models.CharField(max_length=255) class LinkSection(models.Model): page = models.ForeignKey(Page) title = models.CharField(max_length=255) class Link(models.Model): linksection = models.ForeignKey(LinkSection) text = models.CharField(max_length=255) url = models.URLField()
和一个看起来像这样的admin.py:
class LinkInline(admin.TabularInline): model = Link class LinkSectionInline(admin.TabularInline): model = LinkSection inlines = [ LinkInline, ] class PageAdmin(admin.ModelAdmin): inlines = [ LinkSectionInline, ]
我的目标是获得一个管理界面,让我可以在一个页面上编辑所有内容.这个模型结构的最终结果是生成的东西生成一个看起来或多或少的视图+模板:
{{page.title}}
{% for ls in page.linksection_set.objects.all %}{% endfor %}{{ls.title}}
{% for l in ls.link_set.objects.all %}
- {{l.title}}
{% endfor %}
据我所知,我知道Django管理员中的inline-in-an-inline技巧失败了.有谁知道允许这种三级模型编辑的方法?提前致谢.
您需要创建一个自定义表单和模板的LinkSectionInline
.
这样的东西应该适用于表单:
LinkFormset = forms.modelformset_factory(Link) class LinkSectionForm(forms.ModelForm): def __init__(self, **kwargs): super(LinkSectionForm, self).__init__(**kwargs) self.link_formset = LinkFormset(instance=self.instance, data=self.data or None, prefix=self.prefix) def is_valid(self): return (super(LinkSectionForm, self).is_valid() and self.link_formset.is_valid()) def save(self, commit=True): # Supporting commit=False is another can of worms. No use dealing # it before it's needed. (YAGNI) assert commit == True res = super(LinkSectionForm, self).save(commit=commit) self.link_formset.save() return res
(这只是我的头顶而未经过测试,但它应该让你朝着正确的方向前进.)
您的模板只需要适当地呈现表单和form.link_formset.