Django Multiple Inline Embedded Forms

Is it possible?

I need to save some documents that will be restored as json / rest.

A Document has many Sections , and a section has a title, body, and many Images .

Is it possible to create a form with this structure?

 Publication |-- Section |-- Image |-- Image |-- Section |-- Image |-- Section |-- Image |-- Image |-- Image 

My models:

 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) 

I can do this relatively easily when Image is associated with Publication , because there is only one level of nesting.

If Image belongs to Section , I'm not sure how to create the form. There seems to be no easy way to do this with inline forms.

Can anyone help?

+4
source share
1 answer

This cannot be done in vanilla Django. I use django-nested-inlines for this and it works very 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) 
+6
source

Source: https://habr.com/ru/post/1502415/


All Articles