281👍
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 isTrue
.
and the example given is:
def born_in_fifties(self):
return self.birthday.strftime('%Y')[:3] == '195'
born_in_fifties.boolean = True
23👍
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 returnsTrue
,False
, orNone
, Django
will display a pretty “yes”, “no”, or “unknown” icon if you wrap the
method with thedisplay()
decorator passing theboolean
argument with
the value set toTrue
:
class Person(models.Model):
birthday = models.DateField()
@admin.display(boolean=True)
def born_in_fifties(self):
return 1950 <= self.birthday.year < 1960
- [Django]-Error: "dictionary update sequence element #0 has length 1; 2 is required" on Django 1.4
- [Django]-Timestamp fields in django
- [Django]-Django: Example of generic relations using the contenttypes framework?
2👍
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"
- [Django]-How to access a dictionary element in a Django template?
- [Django]-Django/DRF – 405 Method not allowed on DELETE operation
- [Django]-Retrieving parameters from a URL