Django admin - inline inlines (or, three model editing at once)
Asked Answered
X

4

53

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()

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 %}

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.

Xenophanes answered 31/3, 2009 at 19:20 Comment(1)
Could you show your final code with the solution you've accepted?Biochemistry
A
22

You need to create a custom form and template for the LinkSectionInline.

Something like this should work for the form:

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.)

Your template just needs to render the form and form.link_formset appropriately.

Aeolian answered 26/8, 2009 at 5:18 Comment(4)
Can we get sample template code for this answer? Is it advisable to fork Django's change_form.html for this? Also, in Django 1.2.3, the first line should be LinkFormSet = forms.inlineformset_factory(Link)Impala
Hi i am trying to get this to work but am getting errors with LinkFormset not wanting to take instance = self.instance, any reccomendationsSinuate
Brilliant idea to nest the formset in the form. Will be testing that :-)Backslide
TypeError: __init__() got an unexpected keyword argument 'instance' when using it, probably the same as @SinuateFlew
E
5

Django-nested-inlines is built for just this. Usage is simple.

from django.contrib import admin
from nested_inlines.admin import NestedModelAdmin, NestedStackedInline, NestedTabularInline
from models import A, B, C

class MyNestedInline(NestedTabularInline):
    model = C

class MyInline(NestedStackedInline):
    model = B
    inlines = [MyNestedInline,]

class MyAdmin(NestedModelAdmin):
    pass

admin.site.register(A, MyAdmin)
Erivan answered 28/9, 2014 at 18:2 Comment(0)
B
1

My recommendation would actually be to change your model. Why not have a ForeignKey in Link to LinkSection? Or, if it's not OneToMany, perhaps a ManyToMany field? The admin interface will generate that for free. Of course, I don't recommend this if links don't logically have anything to do with link sections, but maybe they do? If they don't, please explain what the intended organization is. (For example, is 3 links per section fixed or arbitrary?)

Biocatalyst answered 4/4, 2009 at 14:5 Comment(1)
Silly me, I ommited the ForeignKey field that I meant to be there :). The links do have to do with the link sections (intended as a header of sorts). The 3 links per section is arbitrary. I'll edit the OP to better reflect this.Xenophanes
B
0

You can create a new class, similar to TabularInline or StackedInline, that is able to use inline fields itself.

Alternatively, you can create new admin templates, specifically for your model. But that of course overrules the nifty features of the admin interface.

Booma answered 25/8, 2009 at 17:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.