PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, April 22, 2022

[FIXED] How to restore integers from my json.dumps file (for display in my javascript chart) when using Django

 April 22, 2022     django, django-views, javascript, pie-chart, python     No comments   

Issue

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.


Solution

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]])


Answered By - Josh Ackland
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing