Stephen Wang
Stephen Wang

Reputation: 33

Getting a django view python dict into highcharts series data

I'm trying to figure out the cleanest way to take a python dict that I have in a django view and get that into a pie chart series in highcharts. Specifically, when I click on a point in one chart on my page, I'm trying to load a second chart with detailed data on that point.

For example, I might have a column chart with inventory for 'fruit', 'meat', 'vegetables'. If I click on a column, a second chart displays the inventory breakdown. AKA The second 'fruit' chart would show the inventory for 'apples', 'oranges', 'bananas' in a pie graph.

I'm trying to do this with jQuery.get since I don't want to reload the entire page. My django view would have a section for handling the ajax that looks something like this:

myData = {}
myData['apples'] = 20
myData['oranges'] = 30
myData['bananas'] = 50

context = Context()
context['fruit'] = myData
return HttpResponse(context)

The data format that I'd like to use for the pie chart has the dict key as the x and dict value as the y:

[['apples',20],['oranges',30]…]

I've tried just passing the data as a string from the view to script, and while that gets across the wire correctly as a string, is not handled the way I want because I think the values 20, 30 etc are handled as strings and not values. I'm not sure if this is the right way at all. Should I be doing this by rendering the context in a django template? If so, how would something like that look like inside a jQuery/ajax success handler?

It seems like going from a dict to a highcharts series with the aforementioned format (with the dict key as the x and dict value as the y) would be something that many folks have done so I think I'm missing something.

Upvotes: 2

Views: 1377

Answers (2)

Coffee
Coffee

Reputation: 1771

If you are using django >= 1.7, JsonResponse will be a better choice.

from django.http import JsonResponse

def my_data(request):
    myData = {}
    myData['apples'] = 20
    myData['oranges'] = 30
    myData['bananas'] = 50
    return JsonResponse(myData, safe=False)

Upvotes: 1

Piotr Kowalczuk
Piotr Kowalczuk

Reputation: 399

Try this:

import json
from django.http import HttpResponse

myData = {}
myData['apples'] = 20
myData['oranges'] = 30
myData['bananas'] = 50

response_data = {
  'data': myData,
  'message': 'OK',
  'status': 'success'
}

return HttpResponse(json.dumps(response_data), content_type="application/json")

Upvotes: 2

Related Questions