快速开始¶
在 5 分钟内创建您的第一个自定义数据看板。本指南将引导您创建一个简单的销售数据看板。
先决条件¶
- 已安装 Django Admin Dashboards(参见 安装)
- 一个正常运行的 Django 项目,带有管理界面
步骤 1:创建数据看板文件¶
在您的 Django 应用程序中创建一个新文件 dashboard.py:
# myapp/dashboard.py
from django_admin_dashboards.base import Dashboard, CardComponent, ChartComponent, Layout
from django.utils.translation import gettext_lazy as _
class SalesDashboard(Dashboard):
"""示例销售数据看板"""
title = _("销售数据看板")
show_dashboard_title = True
show_admin_title = False
def get_layout(self):
"""Define dashboard layout"""
layout = Layout(columns=12)
# 第1行: 卡片 (3个卡片,每列4格)
layout.add_row([
(CardComponent(
title="Total Revenue",
value="$12,450",
change="+24%",
trend="up",
color="primary",
icon_class="ri-money-dollar-circle-line"
), 4),
(CardComponent(
title="Orders",
value=156,
change="+12%",
trend="up",
color="success",
icon_class="ri-shopping-cart-2-line"
), 4),
(CardComponent(
title="Avg. Order Value",
value="$79.80",
change="+8%",
trend="up",
color="warning",
icon_class="ri-trophy-line"
), 4),
], height="auto")
# 第2行: 多值卡片 (6列) + 图表 (6列)
layout.add_row([
(CardComponent(
title="Customer Segments",
values=[85, 42, 29], # Premium, Regular, New
value_labels=["Premium", "Regular", "New"],
color="info",
icon_class="ri-user-star-line"
), 6),
(ChartComponent(
title="Monthly Revenue Trend",
chart_type="line",
data={
"labels": ["Jan", "Feb", "Mar", "Apr", "May", "Jun"],
"datasets": [{
"label": "Revenue",
"data": [8500, 9200, 10200, 12450, 11800, 13500],
"borderColor": "rgb(75, 192, 192)",
"backgroundColor": "rgba(75, 192, 192, 0.1)",
"fill": True,
}]
},
options={
"responsive": True,
"plugins": {
"legend": {"position": "top"},
},
"scales": {
"y": {
"beginAtZero": False,
"title": {
"display": True,
"text": "Revenue ($)"
}
}
}
}
), 6),
], height="400px")
return layout
步骤 2:配置数据看板设置¶
更新您的 settings.py 以使用新的数据看板:
# settings.py
DJANGO_ADMIN_DASHBOARDS = {
"admin:index": "myapp.dashboard.SalesDashboard",
# Optional: Also use for specific app
# "admin:app_list": {
# "myapp": "myapp.dashboard.SalesDashboard",
# },
}
步骤 3:重启服务器并查看¶
重启您的 Django 开发服务器:
访问 http://localhost:8000/admin/ 查看您的新数据看板。
步骤 4: 添加动态数据¶
更新您的数据看板以显示来自模型的真实数据:
# myapp/dashboard.py (updated)
from django_admin_dashboards.base import Dashboard, CardComponent, ChartComponent, Layout, TableComponent
from django.utils.translation import gettext_lazy as _
from django.db.models import Sum, Count
from datetime import datetime, timedelta
from django.utils import timezone
from .models import Order # Assuming you have an Order model
class SalesDashboard(Dashboard):
"""Sales dashboard with real data"""
title = _("Sales Dashboard")
def get_kpi_cards(self):
"""使用数据库数据生成卡片"""
today = timezone.now().date()
last_month = today - timedelta(days=30)
# Calculate metrics from database
total_revenue = Order.objects.aggregate(
total=Sum('amount')
)['total'] or 0
monthly_revenue = Order.objects.filter(
created_at__gte=last_month
).aggregate(
total=Sum('amount')
)['total'] or 0
order_count = Order.objects.count()
monthly_orders = Order.objects.filter(
created_at__gte=last_month
).count()
avg_order_value = total_revenue / order_count if order_count > 0 else 0
return [
CardComponent(
title="Total Revenue",
value=f"${total_revenue:,.2f}",
change=f"+{((monthly_revenue / (total_revenue - monthly_revenue)) * 100):.1f}%" if total_revenue > monthly_revenue else "N/A",
trend="up" if monthly_revenue > 0 else "neutral",
color="primary",
icon_class="ri-money-dollar-circle-line"
),
CardComponent(
title="Total Orders",
value=order_count,
change=f"+{((monthly_orders / (order_count - monthly_orders)) * 100):.1f}%" if order_count > monthly_orders else "N/A",
trend="up" if monthly_orders > 0 else "neutral",
color="success",
icon_class="ri-shopping-cart-2-line"
),
CardComponent(
title="Avg. Order Value",
value=f"${avg_order_value:.2f}",
color="warning",
icon_class="ri-trophy-line"
),
]
def get_chart_data(self):
"""Generate chart data from database"""
# Get last 6 months of data
months = []
revenue_data = []
for i in range(5, -1, -1):
month_start = timezone.now().replace(
day=1, hour=0, minute=0, second=0, microsecond=0
) - timedelta(days=30 * i)
month_end = month_start + timedelta(days=30)
month_revenue = Order.objects.filter(
created_at__gte=month_start,
created_at__lt=month_end
).aggregate(total=Sum('amount'))['total'] or 0
months.append(month_start.strftime('%b'))
revenue_data.append(float(month_revenue))
return {
"labels": months,
"datasets": [{
"label": "Monthly Revenue",
"data": revenue_data,
"borderColor": "rgb(75, 192, 192)",
"backgroundColor": "rgba(75, 192, 192, 0.1)",
"fill": True,
}]
}
def get_recent_orders(self):
"""Get recent orders for table"""
recent_orders = Order.objects.select_related('customer').order_by('-created_at')[:10]
return TableComponent(
title="Recent Orders",
columns=["Order ID", "Customer", "Amount", "Date", "Status"],
data=[
[
f"#{order.id}",
order.customer.name,
f"${order.amount:.2f}",
order.created_at.strftime('%Y-%m-%d'),
order.get_status_display(),
]
for order in recent_orders
]
)
def get_layout(self):
"""Define dashboard layout with dynamic components"""
layout = Layout(columns=12)
# 添加卡片
kpi_cards = self.get_kpi_cards()
layout.add_row([
(kpi_cards[0], 4),
(kpi_cards[1], 4),
(kpi_cards[2], 4),
], height="auto")
# Add chart
layout.add_row([
(ChartComponent(
title="Monthly Revenue Trend",
chart_type="line",
data=self.get_chart_data(),
options={
"responsive": True,
"maintainAspectRatio": False,
"plugins": {
"legend": {"position": "top"},
},
"scales": {
"y": {
"beginAtZero": True,
"title": {
"display": True,
"text": "Revenue ($)"
}
}
}
}
), 12)
], height="400px")
# Add recent orders table
layout.add_row([
(self.get_recent_orders(), 12)
], height="auto")
return layout
步骤 5: 添加URL控制¶
测试您的数据看板上的URL参数控制:
- 深色模式:
http://localhost:8000/admin/?_dark_mode_on=true - 强制亮色模式:
http://localhost:8000/admin/?_dark_mode_on=false - 跟随系统:
http://localhost:8000/admin/?_dark_mode_on=auto - 全屏隐藏:
http://localhost:8000/admin/?_hide_others_in_fullscreen=true(如果启用)
步骤 6: 自定义外观¶
更改卡片颜色¶
CardComponent(
title="Revenue",
value="$12,450",
color="success", # Options: primary, success, warning, danger, info, secondary
icon_class="ri-money-dollar-circle-line"
)
调整布局¶
# Different column spans
layout.add_row([
(component1, 8), # 8 columns wide
(component2, 4), # 4 columns wide
], height="auto")
# Different row heights
layout.add_row([...], height="300px") # Fixed height
layout.add_row([...], height="auto") # Auto height
Example: 完整数据看板示例¶
这是一个包含所有功能的完整示例:
# myapp/dashboard.py
from django_admin_dashboards.base import Dashboard, CardComponent, ChartComponent, Layout, TableComponent, FilterComponent
from django.utils.translation import gettext_lazy as _
from django.db.models import Sum, Count, Q
from datetime import datetime, timedelta
from django.utils import timezone
from .models import Order, Customer
class AdvancedSalesDashboard(Dashboard):
"""Advanced sales dashboard with filters and multiple components"""
title = _("Advanced Sales Dashboard")
show_dashboard_title = True
show_admin_title = False
hide_others_in_fullscreen = True # Enable fullscreen feature
def get_filters(self):
"""Generate filter components"""
return FilterComponent(
title="Dashboard Filters",
filters=[
{
"name": "date_range",
"label": "Date Range",
"type": "select",
"options": [
{"value": "today", "label": "Today"},
{"value": "week", "label": "This Week"},
{"value": "month", "label": "This Month"},
{"value": "quarter", "label": "This Quarter"},
{"value": "year", "label": "This Year"},
],
"default": "month",
},
{
"name": "status",
"label": "Order Status",
"type": "select",
"options": [
{"value": "all", "label": "All Orders"},
{"value": "completed", "label": "Completed"},
{"value": "pending", "label": "Pending"},
{"value": "cancelled", "label": "Cancelled"},
],
"default": "all",
},
],
)
def get_layout(self):
"""Complete layout with all component types"""
layout = Layout(columns=12)
# Filters at top
layout.add_row([
(self.get_filters(), 12)
], height="auto")
# 卡片
kpi_cards = self.get_kpi_cards()
layout.add_row([
(kpi_cards[0], 3),
(kpi_cards[1], 3),
(kpi_cards[2], 3),
(kpi_cards[3], 3),
], height="auto")
# Charts
layout.add_row([
(self.get_revenue_chart(), 6),
(self.get_customer_chart(), 6),
], height="400px")
# Tables
layout.add_row([
(self.get_recent_orders(), 6),
(self.get_top_customers(), 6),
], height="auto")
return layout
# Implement the other methods (get_kpi_cards, get_revenue_chart, etc.)
# ...
下一步¶
成功提示¶
- 从简单开始: 从基础卡片开始,然后添加图表和表格
- 使用真实数据: 连接到您的数据库模型以获取动态数据看板
- 响应式测试: 检查您的数据看板在不同屏幕尺寸下的显示效果
- 逐步启用功能: 逐个添加深色模式、全屏和过滤器
- 监控性能: 使用Django调试工具栏检查查询性能
需要帮助?¶
- 查看用户指南获取详细说明
- 查看示例获取更完整的示例
- 搜索Gitee Issues寻找解决方案