Django管理员 - 内联内联(或三次模型编辑) [英] Django admin - inline inlines (or, three model editing at once)
问题描述
我有一套如下所示的模型:
I've got a set of models that look like this:
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:
and an admin.py that looks like this:
class LinkInline(admin.TabularInline):
model = Link
class LinkSectionInline(admin.TabularInline):
model = LinkSection
inlines = [ LinkInline, ]
class PageAdmin(admin.ModelAdmin):
inlines = [ LinkSectionInline, ]
我的目标是获得一个管理界面,让我在一个页面上编辑所有内容。这个模型结构的最终结果是生成的视图+模板看起来或多或少如下所示:
My goal is to get an admin interface that lets me edit everything on one page. The end result of this model structure is that things are generated into a view+template that looks more or less like:
<h1>{{page.title}}</h1>
{% for ls in page.linksection_set.objects.all %}
<div>
<h2>{{ls.title}}</h2>
<ul>
{% for l in ls.link_set.objects.all %}
<li><a href="{{l.url}}">{{l.title}}</a></li>
{% endfor %}
</ul>
</div>
{% endfor %}
我知道inline-in-in-in-inline trick正如我所料,Django管理员失败。有人知道一种允许这种三级模型编辑的方法吗?感谢提前。
I know that the inline-in-an-inline trick fails in the Django admin, as I expected. Does anyone know of a way to allow this kind of three level model editing? Thanks in advance.
推荐答案
您需要创建一个自定义表单和模板为 LinkSectionInline
。
You need to create a custom form and template for the 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
(刚刚从我的头顶上,没有测试,但它应该让你进去正确的方向。)
(That just came off the top of my head and isn't tested, but it should get you going in the right direction.)
您的模板只需要适当地呈现表单和form.link_formset。
Your template just needs to render the form and form.link_formset appropriately.
这篇关于Django管理员 - 内联内联(或三次模型编辑)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!