5

Is this even possible?

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

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

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 easy when Image is related to Publication, because there is only one level of nesting.

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.

Can anyone help?

Rob L
  • 3,634
  • 2
  • 19
  • 38

1 Answers1

6

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)
hellsgate
  • 5,905
  • 5
  • 32
  • 47
  • Thanks, hellsgate. I'll check into it. My other option may be to make an `Image` library which is separate from the `Section`s. And then use a Javascript routine to associate the `Image`s. – Rob L Sep 16 '13 at 13:43
  • I've added a simple code example for how it would work with the nested inlines. Good luck either way – hellsgate Sep 16 '13 at 13:47
  • I think I looked at django-nested-inlines last week. The thing is, I plan to make my own form for this, rather than django-admin. – Rob L Sep 16 '13 at 13:51
  • Of course, django-nested-inlines is specific to admin so it would need some customisation for use outwith that. It would probably be worthwhile having a look inside the code to work out how it goes about it though, specifically the forms.py. – hellsgate Sep 16 '13 at 14:15
  • 1
    I'm investigating this: http://yergler.net/blog/2013/09/03/nested-formsets-redux/ – Rob L Sep 16 '13 at 15:36