多嵌套内联表单集

多嵌套内联表单集

本文介绍了Django 多嵌套内联表单集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这甚至可能吗?

我需要将一些要检索的文档存储为 json/rest.

I need to store some documents to be retrieved as json/rest.

一个Document有很多Sections,一个section有一个标题、一个body和很多Images.

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)

ImagePublication 相关时,我可以相对容易地做到这一点,因为只有一层嵌套.

I can do this relatively easy when Image is related to Publication, because there is only one level of nesting.

Image 属于 Section 时,我不确定如何构建表单.使用内联表单集似乎没有简单的方法可以做到这一点.

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 多嵌套内联表单集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-28 05:13