victorhooi
victorhooi

Reputation: 17275

Django and Highcharts - Generating charts, and still being DRY?

I'm currently making a server dashboard that relies quite heavily on graphs and charts.

I'm using Django on the backend, and Highcharts/Highstock (http://www.highcharts.com/) for the graphs (although we're also looking at D3, depending on how that progresses).

My question is, what's a good way to generate all our graphs, and still remain DRY?

(I'm aware of Django-Chartit, but it's a bit limited for our purposes and doesn't offer us some of the customisability we'd need).

1. How to retrieve data

Firstly, am I better off encoding the data for the graphs inside the JavaScript itself. E.g.:

series: [{
    name: 'Virtualised',
    data: [80, 81, 84, 84, 85, 80, 90, 85, 80, 88, 89, 90]
    }, {
    name: 'Physical',
    data: [15, 14, 12, 8, 10, 12, 12, 14, 10, 12, 8, 9]
    }]

Or should I be retrieving all data via AJAX calls - e.g. JSON via Query.get()?

2. Generating Javascript Dynamically

If we go with option 1 and encode the data directly into the JavaScript, how do I generate those Javascript files dynamically?

Currently, our JS is being served directly by our web-server (NGinx). Or should I use an inline <script> tag inside my HTML files?

3. Security/Performance with AJAX

If we go down option 2 the JSON/AJAX route - would there be performance issues with making say twenty JQuery.get() calls on one page? I'm not aware of any way to batch them all?

And what about security - we'd like to only expose the AJAX endpoint to the charts, but how can you allow that but not let anybody make a direct call to that URL?

4. DRY

Either way, I've noticed we have a stack-load of repetition with all these charts.

What's the best way to cut-down on this? Template-tags for charts? Or is there a smarter way?

Cheers, Victor

Upvotes: 4

Views: 2259

Answers (1)

ilvar
ilvar

Reputation: 5841

  1. Depends on size of the data. If you have large datasets and do not need to show all charts immediately - surely you should use AJAX. Otherwise, coding into js is okay.
  2. You can add some urls like /data/some_data.js which will be rendered by Django (with or without template system) and provide data in that files. Highcharts scripts will be called below and use that data.
  3. If you use ajax, you can make it same way - retrieve one big pack of data (using hash array, for example) and after that create your charts one by oone using one part of data at a time. For security reason you can use Django's CSRF here - create an empty form with only token in it, and POST it with the request. On the serverside you'll just need to deny GET access to that URL, with class-based views or plain checking of request.method.
  4. If you use one pack of data, you can add a block ID, title and other metadata there and use it when instantiating charts with JS.

Upvotes: 2

Related Questions