How to add 'collapse' to a Django StackedInline

Viewed 12116

In the same way you can add 'classes': ['collapse'] to one of your ModelAdmin fieldsets, I'd like to be able to have an Inline Model Admin be collapsible.

This ticket, Collapse in admin interface for inline related objects, discusses exactly what I want to accomplish. But in the mean time, what's the best work around while we wait for the next release?

FYI: I've come up with a solution, but I think a better one exists. I'll let the voting take care of it.

8 Answers

In modern-day Django this is as easy as the following:

class FooInline(admin.StackedInline):
     model = Foo
     classes = ['collapse']

Here's how I solved it, but it feels too much like a hack (for a hack).

I used jQuery hosted from Google APIs to modify the DOM, taking advantage of Django's own 'show/hide' script. If you look at the html source of an admin page, the last script loaded is this:

<script type="text/javascript" src="/media/admin/js/admin/CollapsedFieldsets.js"></script>

The comments in that file gave me the idea: Leverage ModelAdmin media definitions to load my own dom-altering script.

from django.contrib import admin
from django.contrib.admin.sites import AdminSite
from myapp.models import *
import settings
media = settings.MEDIA_URL

class MyParticularModelAdmin(admin.ModelAdmin):
    # .....
    class Media:
          js = ('http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js',
              media+'js/addCollapseToAllStackedInlines.js')
# .....

And then inside of the referenced javascript file:

// addCollapseToAllStackedInlines.js
$(document).ready(function() {
  $("div.inline-group").wrapInner("<fieldset class=\"module aligned collapse\"></fieldset>");
});

The end results only works on StackedInline, NOT TabularInline.

If you want collapsible inline model then,

class AAAAdmin(admin.StackedInline):
    model = AAA
    classes = ['collapse', 'show']

If you want the grouping of fields collapsible then,

fieldsets = (
    ("Basic Details", {'fields': (
        "title", "street_line1", "street_line2", "city", "state", "country", "zipcode",
        "additional_code", "zone", "contact_no"
    )}),
    ("Google Map Related Details", {"classes": ['collapse', 'show'], 'fields': (
        "location", "longitude", "latitude", "google_map_link"
    )}),
)
Related