Skip to content

Instantly share code, notes, and snippets.

@adityarao310
Last active August 21, 2018 15:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adityarao310/448cadc8f2691cd69b667e7418d33f1a to your computer and use it in GitHub Desktop.
Save adityarao310/448cadc8f2691cd69b667e7418d33f1a to your computer and use it in GitHub Desktop.
Integrate Django app data with Google Charts API
<!-- At the bottom of your page as usual, insert chart.js so that when html loads the chart is loaded -->
<body>
<!-- django template block to insert the block if you are using base template -->
{% block chart %}
{% endblock %}
<!-- Scripts required to run the page -->
<script type="text/javascript" src="{% static '/habit_app/js/chart.js' %}"></script>
</body>
/* Fetch the URL using fetch api in javascript now and process it as you wish. The code below shows how to do it for use in the default chart function */
//1. Google Charts only works on array so you have to convert the json into an array later
//2. Use var=options to style your chart as usual
//3. Use js promises to process the url and the json you fetch
function line(arrayofarray) {
// global function to draw a line chart on an array
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable(arrayofarray);
var options = {
// enter styling options here. check allowed syntax from official doc
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
}
const url = '/api/data';
fetch(url)
.then(response => response.json())
.then(data => {
objarray = data.results;
})
.then(sorted_array => {
var chart_array = [['Date', 'Pain']];
objarray.forEach(element => {
var small_array = [];
small_array[0] = outputDate(element.task_creation_date);
small_array[1] = parseInt(element.task_painmood_level); // my model had to convert string to int
chart_array.push(small_array);
});
line(chart_array);
})
.catch((error) => {
console.log("There was an error", error);
})
''' The data generated in get_data has to come to a URL, right? Define that here'''
urlpatterns = [
path(r'api/data', views.get_data, name='api-data'),
]
''' Add the function below to views file to generate a JSON response from a queryset to be used by Google Charts'''
#1. Use "import HttpResponse" if you are not using Python 3.x
#2. Adding .values at end of queryset helps you choose attributes in JSON response e.g. the query below will only add level and date; and skip other stuff like name, type etc in the model
#3. list(results) will help you remove extra quotation marks which occurs when you serialise. If you are serialising an object which is not a dictionary, you have to set safe parameter to False
from django.http import JsonResponse
def get_data(request):
'''This is a sample query set on a table called Task, filtered for'''
result = Task.objects.filter(task_focusmapped=2).order_by('task_creation_date').values('task_level', 'task_date')
results = result.filter(Q(task_status='do') | Q(task_status='no'))
return JsonResponse({'results': list(results)}, safe=False)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment