如何在Django中设置查询参数并动态更新Chart.js图表
实现Django+Chart.js日期筛选动态更新图表的步骤
1. 前端日期筛选器HTML结构
先在模板中定义日期输入框和图表画布:
<!-- 日期筛选区域 --> <div class="date-filter"> <label>起始日期:</label> <input type="date" id="from-date" required> <label>结束日期:</label> <input type="date" id="to-date" required> <button id="filter-btn">筛选数据</button> </div> <!-- Chart.js渲染画布 --> <canvas id="data-chart" width="800" height="400"></canvas>
2. 后端Django接口配置
视图层代码
编写视图接收from、to日期参数,返回筛选后的图表所需JSON数据:
from django.http import JsonResponse from .models import YourBusinessModel # 替换为自己的业务模型 from django.utils.dateparse import parse_date def get_chart_data(request): # 直接从GET请求中获取日期参数,和你需求的取值方式完全匹配 from_date = parse_date(request.GET.get('from', '')) to_date = parse_date(request.GET.get('to', '')) # 替换为自己的业务筛选逻辑,date_field为你模型中存储日期的字段 queryset = YourBusinessModel.objects.filter(date_field__range=[from_date, to_date]) # 处理为Chart.js需要的格式,可根据自己的需求调整字段 labels = [item.date_field.strftime('%Y-%m-%d') for item in queryset] values = [item.business_value for item in queryset] return JsonResponse({'labels': labels, 'values': values})
路由配置
在urls.py中注册接口地址:
from django.urls import path from . import views urlpatterns = [ # 其他原有路由 path('api/chart-data/', views.get_chart_data, name='chart_data'), ]
3. 前端JS实现参数传递与动态更新
引入Chart.js后编写逻辑,监听筛选操作,传递日期参数、拉取数据并更新图表:
// 全局保存图表实例,避免重复渲染 let chartInstance = null; // 图表初始化/更新方法 function renderChart(labels = [], values = []) { const ctx = document.getElementById('data-chart').getContext('2d'); // 销毁旧实例 if (chartInstance) chartInstance.destroy(); // 渲染新图表,可替换为你需要的图表类型、样式配置 chartInstance = new Chart(ctx, { type: 'line', data: { labels: labels, datasets: [{ label: '数据统计', data: values, borderColor: 'rgb(75, 192, 192)', tension: 0.1 }] } }); } // 页面首次加载初始化空图表 renderChart(); // 监听筛选按钮点击事件 document.getElementById('filter-btn').addEventListener('click', function() { const fromVal = document.getElementById('from-date').value; const toVal = document.getElementById('to-date').value; // 基础日期校验 if (!fromVal || !toVal || new Date(fromVal) > new Date(toVal)) { alert('请选择合法的日期范围'); return; } // 构造带查询参数的请求地址,encodeURIComponent规避特殊字符问题 const requestUrl = `/api/chart-data/?from=${encodeURIComponent(fromVal)}&to=${encodeURIComponent(toVal)}`; // 发起请求更新图表 fetch(requestUrl) .then(res => res.json()) .then(data => { renderChart(data.labels, data.values); }) .catch(err => console.error('数据请求失败:', err)); });
补充说明:如果不需要点击按钮,想选完日期自动刷新图表,只需要把点击事件的监听逻辑,绑定到两个日期输入框的
change事件上即可。
内容的提问来源于stack exchange,提问作者Supraja
相关产品推荐
相关产品推荐

