开发者

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

In change list view in django ad开发者_开发百科min 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?


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.


This is an old question but I'll add an example from docs for Django 1.10 because allow_tags attribute used in the accepted answer is deprecated since Django 1.9 and it is recommended to use format_html instead:

from django.db import models
from django.contrib import admin
from django.utils.html import format_html

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

    def colored_name(self):
        return format_html(
            '<span style="color: #{};">{} {}</span>',
            self.color_code,
            self.first_name,
            self.last_name,
        )

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


In addition you can use

colored_first_name.short_description = 'first name'

For a nice column title

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜