Reputation: 314
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?
Upvotes: 7
Views: 10720
Reputation: 1357
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')
Upvotes: 7
Reputation: 124
In addition you can use
colored_first_name.short_description = 'first name'
For a nice column title
Upvotes: 2
Reputation: 29400
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.
Upvotes: 11