12

In the Django admin if the field is a BooleanField or NullBooleanField, Django will display a pretty "on" or "off" icon instead of True or False.

Now, I don't really have a BooleanField in my model by I do have a property fior which I'd like to display the icons but when I try doing so, Django screams that 'SomeAdmin.list_filter[0]' refers to 'is_activated' which does not refer to a Field.

Is it possible to display those nice little icons for this field without hacking Django too much.

Thanks

Mridang Agarwalla
  • 43,201
  • 71
  • 221
  • 382

2 Answers2

34

You don't want to use list_filter. The property you're looking for is list_display. The documentation offers an example of how you can create a column that behaves like a boolean in the display. In short, you do something like this:

  1. Create a method in the class:

    def is_activated(self)
        if self.bar == 'something':
            return True
        return False
    
  2. add the .boolean method attribute directly below the is_activated method:

    is_activated.boolean = True
    
  3. Add the method as a field in list_display:

    class MyAdmin(ModelAdmin): list_display = ['name', 'is_activated']

  4. You'll notice the column name is probably now "Is Activated" or something like that. If you want the column heading to change, you use the short_description method attribute:

    is_activated.short_description = "Activated"
    
Jordan Reiter
  • 20,467
  • 11
  • 95
  • 161
  • 2
    I'll add that method attributes like these are a fascination of mine, see my related question: http://stackoverflow.com/questions/7337681/method-attributes-in-django – Jordan Reiter Sep 19 '11 at 16:54
  • HI Jordan, this did it but I was wondering whether I have to have a method in my admin class for each custom property in my model class? The `is_activated` is already declared in my Model. Thanks. – Mridang Agarwalla Sep 19 '11 at 16:59
  • They can be declared in your model or your `ModelAdmin` class. The documentation I linked to actually states this. – Jordan Reiter Sep 19 '11 at 17:27
  • 2
    A bit late to the party, but `def is_activated(self): return self.bar == 'something'` is a bit shorter :) – Alex Szabo Sep 08 '16 at 12:51
5

The correct way to do this now in Django 3.0+ is with @admin.display.

    @admin.display(
      boolean=True,
      ordering='-publish_date',
      description='Is Published?', 
    ) 
    def is_published(self, obj):
        return obj.publish_date is not None
blakev
  • 4,154
  • 2
  • 32
  • 52