In my Django application, I have a very basic pie chart model with the name column as a CharField and the stats column as an IntegerField. I also have some JavaScript code on my html page that displays a pie chart -- but I'm only able to get it working if I hardcode the values as an array. I was hoping to instead display the data from my model/ DB as {{ values|safe }}
in pie chart form, pulling the values from json dumps of my DB data.
Here's what I've tried, as seen in my views.py file:
def metrics(request):
pietitle = serializers.serialize('json', PieChart.objects.all(),fields=('title'))
piestats = serializers.serialize('json', PieChart.objects.all(),fields=('stats'))
piedata=[[pietitle, piestats]]
json_data = json.dumps(piedata)
data_json= json.loads(json_data)
return render(request, "metrics.html", {"values": data_json})
On my HTML page, the message I'm getting is simply "No Data", and I'm fairly certain that's because when I serialize the stats field, it's converted to a string and is unable to be interpreted as integers.
Make sure the data is in the correct format for the pie chart.
With this line piedata=[[pietitle, piestats]]
, if you wanted to access the first title you'd have to go data_json[0][0][0]
and for the first lot of stats you'll have to go data_json[0][1][0]
Edit answer based on comment:
piedata = []
for i in range(len(pietitle)):
piedata.append([pietitle[i], piestats[I]])