Highcharts动态添加Series问题求助(Django+JS实现)
Hey there! Let's walk through how to dynamically generate Highcharts series from your dictionary data in your Django + HTML/JS setup. I'll break this into backend and frontend steps to make it clear.
Step 1: Prepare & Process Data in Django Backend
First, we need to convert your raw dictionary data into a format Highcharts understands—specifically, turning date strings into millisecond timestamps (since Highcharts uses milliseconds for datetime axes) and converting your second values to milliseconds (matching your y-axis's datetime type).
In your Django view, add this processing logic:
from datetime import datetime import json def your_time_tracking_view(request): # Example raw dictionary (replace with your actual data source) raw_task_data = { "Fiber_Mätning": [ {"x": "2020-10-28", "y": "28800"}, {"x": "2020-10-29", "y": "18000"} ], "Backend_Development": [ {"x": "2020-10-28", "y": "14400"}, {"x": "2020-10-30", "y": "36000"} ] } # Process data into Highcharts-ready format processed_series = [] for task_name, points in raw_task_data.items(): formatted_points = [] for point in points: # Convert date string to millisecond timestamp date_obj = datetime.strptime(point["x"], "%Y-%m-%d") x_timestamp = date_obj.timestamp() * 1000 # Highcharts requires ms # Convert seconds to milliseconds (matches y-axis datetime type) y_milliseconds = int(point["y"]) * 1000 formatted_points.append({"x": x_timestamp, "y": y_milliseconds}) processed_series.append({ "name": task_name, "data": formatted_points }) # Pass processed data to your template context = { "user_to_show": request.user.username, # Or your target user "all_dates": json.dumps(["2020-10-28", "2020-10-29", "2020-10-30"]), "extra_info": json.dumps({}), # Your existing extra info "dynamic_series": json.dumps(processed_series) } return render(request, "your_template.html", context)
Step 2: Update Frontend Highcharts Initialization
Now, replace your static series: [{ }] with the processed data from Django. I'll also tweak the x-axis to use Highcharts' datetime type (more reliable for date handling than categories):
<script> // Keep your existing secondsTimeSpanToHMS function here $('#container').highcharts({ chart:{ type: 'column', events:{ load: function(){ RedrawColumns(this) }, redraw: function(){ RedrawColumns(this) } } }, title:{ text: 'Time worked by {{user_to_show}}' }, subtitle:{ text:'{{user_to_show}}´s flex time: ' }, tooltip:{ formatter: function (){ // Format the x timestamp back to a readable date const dateStr = new Date(this.x).toISOString().split('T')[0]; var text = 'Date: ' + dateStr + '<br>' + 'Time: ' + secondsTimeSpanToHMS(this.y/1000) + '<br>' + 'Extra info:' + {{extra_info|safe}}[dateStr]; return text; } }, xAxis: { type: 'datetime', // Switch to datetime type for better date handling labels: { format: '{value:%Y-%m-%d}' // Display dates in your desired format } }, yAxis: [{ title: { text: '' }, gridLineWidth: 1, type: 'datetime', dateTimeLabelFormats: { second: '%H:%M:%S', minute: '%H:%M:%S', hour: '%H:%M:%S', day: '%H:%M:%S', week: '%H:%M:%S', month: '%H:%M:%S', year: '%H:%M:%S' }, opposite: true }], plotOptions: { series: { dataLabels: { enabled: true, formatter: function() { // Show time in HH:MM:SS for all series (adjust if needed) return secondsTimeSpanToHMS(this.y/1000); } } } }, series: {{ dynamic_series|safe }} // Use the processed series from Django }); </script>
Key Notes
- Datetime Axes: Using
type: 'datetime'for the x-axis lets Highcharts handle date sorting and formatting automatically, which is more robust than hardcoding categories. - Data Safety: Always use
|safewhen passing JSON from Django to JS to avoid unwanted escaping of characters. - Flexibility: This setup will automatically generate a series for every key in your dictionary—no need to manually add new series as your data grows.
内容的提问来源于stack exchange,提问作者Sebastian_Svensson

