Django多个嵌套在线表单 [英] Django Multiple Nested inline formsets
问题描述
这是否可能?
我需要存储一些要检索的文件作为json / rest。
I need to store some documents to be retrieved as json/rest.
A 文件
有许多部分
,而一个部分有一个标题,一个正文和许多图片
。
A Document
has many Sections
, and a section has a heading, a body and many Images
.
有没有办法可以使用这种结构的表单?
Is there a way I can make a form with this structure?
Publication
|-- Section
|-- Image
|-- Image
|-- Section
|-- Image
|-- Section
|-- Image
|-- Image
|-- Image
我的模型:
class Publication(models.Model):
title = models.CharField(max_length=64)
class Section(models.Model):
publication = models.ForeignKey(Publication)
heading = models.CharField(max_length=128)
body = models.TextField()
class Image(models.Model):
section = models.ForeignKey(Section)
image = models.ImageField(upload_to='images/')
caption = models.CharField(max_length=64, blank=True)
alt_text = models.CharField(max_length=64)
当 Image
与相关的出版物
时,因为只有一个级别的嵌套。
I can do this relatively easy when Image
is related to Publication
, because there is only one level of nesting.
当 Image
属于 / code>,但是,我不知道如何构建表单。
似乎没有简单的方法来做这个内联表单。
When Image
is belongs to Section
, though, I'm not sure how to build the form.
It seems as though there's no easy way to do this with inline formsets.
任何人都可以帮助?
推荐答案
这不能在vanilla Django中完成。我使用 django-nested-inlines ,它的效果非常好。
This can't be done in vanilla Django. I use django-nested-inlines for this and it works really well.
from django.contrib import admin
from nested_inlines.admin import NestedModelAdmin, NestedTabularInline
from my.models import Publication, Section, Image
class ImageInline(NestedTabularInline):
model = Image
class SectionInline(NestedTabularInline):
model = Section
inlines = [ImageInline,]
class PublicationAdmin(NestedModelAdmin):
inlines = [SectionInline,]
admin.site.register(Publication, PublicationAdmin)
这篇关于Django多个嵌套在线表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!