1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
| # admin.py - 增强的管理后台
from django.contrib import admin
from django.db.models import Count
from django.utils.html import format_html
@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
list_display = ['name', 'category', 'price', 'stock_status', 'image_preview']
list_filter = ['category', 'is_active', 'created_at']
search_fields = ['name', 'description']
ordering = ['-created_at']
# 自定义字段
def stock_status(self, obj):
if obj.stock > 50:
color = 'green'
elif obj.stock > 10:
color = 'orange'
else:
color = 'red'
return format_html(
'<span style="color: {};">{}</span>',
color,
obj.stock
)
def image_preview(self, obj):
if obj.image:
return format_html(
'<img src="{}" width="50" height="50" />',
obj.image.url
)
return "无图片"
# 批量操作
actions = ['make_active', 'make_inactive']
def make_active(self, request, queryset):
queryset.update(is_active=True)
make_active.short_description = "设为激活"
# 自定义表单
fieldsets = (
('基本信息', {
'fields': ('name', 'category', 'description')
}),
('价格和库存', {
'fields': ('price', 'discount_rate', 'stock')
}),
('媒体', {
'fields': ('image', 'gallery')
}),
)
|