Widget: ItemList
The ItemList
widget is designed to render a list of objects, similar to a Django ModelAdmin
changelist. It's highly versatile and can display data from model querysets, dictionaries, namedtuples, or simple lists/tuples.
Basic Configuration
from controlcenter import widgets
from .models import MyModel
class MyItemList(widgets.ItemList):
# The data source
model = MyModel
queryset = MyModel.objects.filter(is_active=True)
# Columns to display
list_display = ('id', 'name', 'created_at', 'custom_method')
Key Properties
-
list_display
: A tuple or list of strings representing the attributes or dictionary keys to display as columns. It can also include methods from the widget or the model. -
list_display_links
: A tuple or list of field names that should be linked to the object's admin change page. If omitted, the first column inlist_display
is linked by default. -
sortable
: A boolean. If set toTrue
, the table becomes sortable on the client-side using JavaScript. The default isFalse
. -
empty_message
: A string to display if thevalues
list is empty. Defaults to'No items to display'
.
Using Callables in list_display
Just like in ModelAdmin
, you can include methods from your widget or model in list_display
. These methods receive the object for that row as an argument.
You can also add attributes to these methods to control their appearance:
short_description
: Sets the column header text.allow_tags
: IfTrue
, the method's return value will not be HTML-escaped.
from django.utils.html import format_html
from controlcenter import app_settings
class RecentOrders(widgets.ItemList):
model = Order
list_display = (app_settings.SHARP, 'id', 'customer_name', 'total_price', 'status_badge')
sortable = True
def status_badge(self, obj):
if obj.status == 'shipped':
color = 'green'
elif obj.status == 'pending':
color = 'orange'
else:
color = 'grey'
return format_html('<span style="color:{};">●</span> {}', color, obj.get_status_display())
status_badge.short_description = 'Status'
status_badge.allow_tags = True
Row Numbering
To add an auto-incrementing row number column, include app_settings.SHARP
(which defaults to '#'
) in your list_display
tuple.
from controlcenter import app_settings
class MyItemList(widgets.ItemList):
list_display = (app_settings.SHARP, 'name', 'email')