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

In the change list window in the django admin interface, can some fields / lines be marked in red if they reach the expression?

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

+6
django django-models django-admin
source share
3 answers

To change how and what is displayed in the change list window, you can use the list_display version of ModelAdmin .

Keep in mind that columns specified in list_display , which are not real database fields, cannot be used for sorting, so you need to give the Django administrator a hint about which database field to actually use for sorting.

This is done by setting the admin_order_field attribute admin_order_field callee used to transfer some value to HTML, for example.

Example from Django docs for bright 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 this helps.

+9
source share

Alternatively, you can use

 colored_first_name.short_description = 'first name' 

For a good column heading

+2
source share

This is an old question, but I will add an example from the docs for Django 1.10 , because the allow_tags attribute used in the accepted answer is deprecated with 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') 
+1
source share

All Articles