I'm currently working on creating a chart web page using Django and Chart.js within the views.py file of the Django framework.
class ChartView(TemplateView):
template_name = 'graph.html'
def get_context_data(self, **kwargs):
context = super(ChartView, self).get_context_data(**kwargs)
context['labels'] = ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"]
context['datas'] = [12, 19, 3, 5, 2, 3]
return context
When it comes to the html file (template file)
<script>
$( document ).ready(function() {
var data = {
labels: {{ labels }},
datasets: [
{
label: "Site Registrations in the Last 30 Days",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: {{ datas }}
}
]
};
var ctx = document.getElementById("myChart").getContext("2d");
var myLineChart = new Chart(ctx).Line(data);
});
</script>
An error is occurring during the rendering of the html page. The page source displays this:
<script>
$( document ).ready(function() {
var data = {
labels: [u'Red', u'Blue', u'Yellow', u'Green', u'Purple', u'Orange'],
datasets: [
{
label: "Site Registrations in the Last 30 Days",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: [12, 19, 3, 5, 2, 3]
}
]
};
var ctx = document.getElementById("myChart").getContext("2d");
var myLineChart = new Chart(ctx).Line(data);
});
</script>
The issue lies with the data values being correctly displayed as {{ datas }}, while the labels receive incorrect values as {{ labels }}. I'm unsure of how to properly parse the string in Ajax/JavaScript. Any guidance on resolving this issue would be greatly appreciated. Thank you.