Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change font/color for a field in django admin interface if expression is True

In change list view in django admin interface, is it possible to mark some fields/rows red in if they achieve a expression?

For example, if there is a model Group with members and capacity, how can I visualize when they are full or crowded?

like image 850
kelvan Avatar asked Aug 09 '10 18:08

kelvan


1 Answers

For modifying how and what is displayed in change list view, one can use list_display option of ModelAdmin.

Mind you, columns given in list_display that are not real database fields can not be used for sorting, so one needs to give Django admin a hint about which database field to actually use for sorting.

One does this by setting admin_order_field attribute to the callable used to wrap some value in HTML for example.

Example from Django docs for colorful fields:

class Person(models.Model):
    first_name = models.CharField(max_length=50)
    color_code = models.CharField(max_length=6)

    def colored_first_name(self):
        return '<span style="color: #%s;">%s</span>' % (
                             self.color_code, self.first_name)
    colored_first_name.allow_tags = True
    colored_first_name.admin_order_field = 'first_name'

class PersonAdmin(admin.ModelAdmin):
    list_display = ('first_name', 'colored_first_name')

I hope some of this helps.

like image 180
Davor Lucic Avatar answered Sep 28 '22 02:09

Davor Lucic