I am trying to create a dashboard where I can analyse my model's data (Article) using the library plotly.
The Plotly bar chart is not showing on my template, I am wondering if I am doing something wrong since there's no error with the code below :
models.py
from django.db import models
from django.contrib.auth.models import User
import plotly.plotly as py
import plotly.graph_objs as go
class Article(models.Model):
user = models.ForeignKey(User, default='1')
titre = models.CharField(max_length=100, unique=True)
slug = models.SlugField(max_length=40)
likes = models.ManyToManyField(User, related_name="likes")
def __str__(self):
return self.titre
@property
def article_chart(self):
data = [
go.Bar(
x=[self.titre], #title of the article
y=[self.likes.count()] #number of likes on an article
)
]
plot_url = py.plot(data, filename='basic-bar')
return plot_url
dashboard.html
<div>{{ article.article_chart }}</div>
Why is the bar chart not visible? Any suggestion ?
The result of
py.plot(data, filename='basic-bar')
is to generate a offline HTML file and return a local URL of this file
e.g. file:///your_project_pwd/temp-plot.html
If you want to render it in Django framework, you need to
<iframe>
and restructure of your folder in Django settingsOR
data
There is a example which I had tried:
figure_or_data = [Scatter(x=[1, 2, 3], y=[3, 1, 6])]
plot_html = plot_html, plotdivid, width, height = _plot_html(
figure_or_data, True, 'test', True,
'100%', '100%')
resize_script = ''
if width == '100%' or height == '100%':
resize_script = (
''
'<script type="text/javascript">'
'window.removeEventListener("resize");'
'window.addEventListener("resize", function(){{'
'Plotly.Plots.resize(document.getElementById("{id}"));}});'
'</script>'
).format(id=plotdivid)
html = ''.join([
plot_html,
resize_script])
return render(request, 'dashboard.html', {'html': html,})