Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Collapse Just One Field in Django Admin?

The django admin allows you to specify fieldsets. You properly structure a tuple that groups different fields together. You can also specify classes for certain groups of fields. One of those classes is collapse, which will hide the field under a collapsable area. This is good for hiding rarely used or advanced fields to keep the UI clean.

However, I have a situation where I want to hide just one lonesome field on many different apps. This will be a lot of typing to create a full fieldset specification in every admin.py file just to put one field into the collapsed area. It also creates a difficult maintenance situation because I will have to edit the fieldset every time I edit the associated model.

I can easily exclude the field entirely using the exclude option. I want something similar for collapse. Is this possible?

like image 894
Apreche Avatar asked Nov 06 '22 15:11

Apreche


1 Answers

Django doesn't have a built in way of doing this that I'm aware of but I can think of a couple of ways you could do something once, rather than having to manually modify lots of fieldsets.

One approach would be to use javascript to rewrite the page markup. Maybe the javascript could have a list of fieldnames and whenever it finds one of those it hides the field and it's label and adds a button to the page to toggle these invisible fields.

The other approach would just involve python. Normally you just specify the fieldsets attribute in the admin as a tuple. But you could specify it as an imported function which takes the usual tuple as an argument. In your settings file you could specify a list of fieldnames you want to hide. You then need to write a function that returns a modified tuple, moving any fields that match one of your fieldnames into a new fieldset along with the collapse class.

For example in your admin class you could do something like this (you need to write and import hide_fields).

fieldsets = hide_fields(
    (None,
        {'fields':('title', 'content')}
    )
)

This might end up being interpreted as the following, assuming content is in the settings file as something you want to hide:

fieldsets = (
    (None,
        {'fields':('title',)}
    ),
    ('Extra',
        {
            'fields':  ('content',),
            'classes':('collapse',),
        }
    ),
)
like image 80
Garethr Avatar answered Nov 11 '22 05:11

Garethr