list_display - boolean icons for methods

DjangoDjango Admin

Django Problem Overview


When defining the list_display array for a ModelAdmin class, if a BooleanField or NullBooleanField is given the UI will use nice looking icons instead of True/False text in the column. If a method that returns a boolean is given, however, it simply prints out True/False.

Is there a way to make it use the pretty icons for a boolean method?

Django Solutions


Solution 1 - Django

This is documented, although it's a bit hard to find - go a couple of screens down from here, and you'll find this:

> If the string given is a method of the model, ModelAdmin or a callable that returns True or False Django will display a pretty "on" or "off" icon if you give the method a boolean attribute whose value is True.

and the example given is:

def born_in_fifties(self):
    return self.birthday.strftime('%Y')[:3] == '195'
born_in_fifties.boolean = True

Solution 2 - Django

Thanks to @daniel-roseman (rtfm)
Since Django 3.2 there is a decorator @admin.display(boolean=True):

> If the string (in list_display) given is a method of the model, > ModelAdmin or a callable that returns True, False, or None, Django > will display a pretty “yes”, “no”, or “unknown” icon if you wrap the > method with the display() decorator passing the boolean argument with > the value set to True:

class Person(models.Model):
    birthday = models.DateField()

    @admin.display(boolean=True)
    def born_in_fifties(self):
        return 1950 <= self.birthday.year < 1960

Solution 3 - Django

I got this to work for me (Django 3.1.10)

class MyAdmin(MyModel):
    list_display = ("field_as_boolean", )
    
    def field_as_boolean(self, obj):
        return True if obj.field else False
    field_as_boolean.boolean = True
    field_as_boolean.short_description = "field_name"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJason McClellanView Question on Stackoverflow
Solution 1 - DjangoDaniel RosemanView Answer on Stackoverflow
Solution 2 - DjangoDenisView Answer on Stackoverflow
Solution 3 - DjangoShmueltView Answer on Stackoverflow