Reputation: 2102
I have two models: User and Data. Each user has multiple data, and one data belongs to a User.
So I have the following code:
class User(models.Model):
id = models.CharField(max_length=10, primary_key=True)
def __str__(self):
return self.id
class Data(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
timestamp = models.IntegerField(default=0)
x = models.IntegerField(default=0)
y = models.IntegerField(default=0)
z = models.IntegerField(default=0)
def __str__(self):
return 'User : ' + self.user.id + ' | Time : '+ str(self.timestamp)
On my web application, I have a landing page that shows up all users. Once clicked a user, it shows another empty page. I would like to draw a line chart showing the user x,y,z accelerations over the time on that page.
What is the best way of doing this?
Upvotes: 4
Views: 4188
Reputation: 2175
You can use django-nvd3 like this as they have stated in the documentation...
from django.shortcuts import render_to_response
import random
import datetime
import time
def demo_linechart(request):
"""
lineChart page
"""
start_time = int(time.mktime(datetime.datetime(2012, 6, 1).timetuple()) * 1000)
nb_element = 100
xdata = range(nb_element)
xdata = map(lambda x: start_time + x * 1000000000, xdata)
ydata = [i + random.randint(1, 10) for i in range(nb_element)]
ydata2 = map(lambda x: x * 2, ydata)
tooltip_date = "%d %b %Y %H:%M:%S %p"
extra_serie = {"tooltip": {"y_start": "", "y_end": " cal"},
"date_format": tooltip_date}
chartdata = {'x': xdata,
'name1': 'series 1', 'y1': ydata, 'extra1': extra_serie,
'name2': 'series 2', 'y2': ydata2, 'extra2': extra_serie}
charttype = "lineChart"
data = {
'charttype': charttype,
'chartdata': chartdata
}
return render_to_response('linechart.html', data)
Template example:
{% load static %}
<link media="all" href="{% static 'nvd3/src/nv.d3.css' %}" type="text/css" rel="stylesheet" />
<script type="text/javascript" src='{% static 'd3/d3.min.js' %}'></script>
<script type="text/javascript" src='{% static 'nvd3/nv.d3.min.js' %}'></script>
{% load nvd3_tags %}
<head>
{% load_chart charttype chartdata "linechart_container" True "%d %b %Y %H" %}
</head>
<body>
{% include_container "linechart_container" 400 600 %}
</body>
But I think the best way to use django-rest-framework to create api in the backend and
then consume the data of api by any frontend framework like angularjs
and there are several third party open source projects available in frontend frameworks which can help you achieve any kind of chart
Upvotes: 1
Reputation: 151
You can user Chart.js or Google charts on your HTML template, and you need to generate Json, for charts on your Django views.
from django.core.serializers import serialize
data = Data.objects.filter(user=user)
json_data = serialize('json', data, cls=LazyEncoder)
Upvotes: 2