score:9
You don't necessarily need to use serializers to render dynamic data in Chart.js (although you can if you would like). You can just iterate through your Django context variables like normal in the appropriate locations. Below is a line chart example. I would play around with this example, but this should show you how to easily render dynamic data with Django context variables.
...
<canvas id="funchart" width="75" height="50"></canvas>
<script type="text/javascript">
var a = document.getElementById('funchart').getContext('2d');
var myLineChart = new Chart(a, {
type: 'line',
data: {
labels:[{% for i in myobject %}{{ i.labels }},{% endfor %}],
datasets: [{
label:'My Dot',
data: [{% for i in myobject %}{{ i.data }},{% endfor %}]
}]
},
options:{
scales: {
xAxes: [{
display:true
}],
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
</script>
score:1
My code below is what ultimately solved the problem on how to get dynamic user data. I am still trying to figure out how to get the labels to work properly. This solution allows the labels to display with ID numbers, which isn't optimal, but I opened a separate SO for the label issue.
My HTML
{% extends 'base5.html' %}
{% block body_block %}
<div class="box6">
<h1 class="title">Number of Books By Author</h1>
<canvas id="myChart"></canvas>
<div>
<script>
var endpoint = '{% url "Books:chart_data" %}'
var defaultData = [];
var labels = [];
array = {{ procedures3 }}
$.ajax({
method: "GET",
credentials: 'same-origin',
url: endpoint,
success: function(data){
defaultData = data.default
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: [{% for i in book %}{{ i.id }},{% endfor %}],
datasets: [{
label: "# of Procedures",
data: [{% for j in book_count %}
{{ j }},
{% endfor %}],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
}
})
},
error: function(error_data){
console.log("error")
console.log(error_data)
},
})
</script>
{% endblock %}
Views.py
ChartView
class ChartData(LoginRequiredMixin,APIView):
model = Author
authentication_classes = (SessionAuthentication, BasicAuthentication)
permission_classes = (IsAuthenticated,)
def get(self, request, format=None):
default_items = []
labels = []
data = {
"labels": labels,
"default": default_items,
}
return Response(data)
The ChartView
class ChartView(LoginRequiredMixin, TemplateView): template_name = 'Book/chart.html'
def get_context_data(self, **kwargs):
context = super(ChartView, self).get_context_data(**kwargs)
book = Author.objects.filter(id__in=self.request.user.userprofile.author.all()).order_by('id')
books_count = [ Book.objects.filter(author=cls).count() for cls in book ]
context['book'] = book
context['book_count'] = books_count
return context
score:3
so i have been working the same stuff here, i think your label not showing up because the label on chart.js only wants a string, so try this on your labels:
labels: [{% for i in book %}"{{ i.id }}",{% endfor %}]
Source: stackoverflow.com
Related Query
- Django and ChartJS
- Django and Chartjs template conflict
- Chartjs v2 - format tooltip for multiple data sets (bar and line)
- ChartJS canvas not displaying rgba colors in IE, Safari and Firefox
- Chartjs 2 - Stacked bar and unstacked line on same chart with same y axis
- chartjs datalabels change font and color of text displaying inside pie chart
- Change point size and color on hover in chartjs
- ChartJS and jsPDF - why the background is black?
- how to change background in chartjs and remove background lines?
- chartjs - top and bottom padding of a chart area
- How to change the color of legend in chartjs and be able to add one more legend?
- Usage of ChartJS v3 with TypeScript and Webpack
- Category scale on Y-axis and time on x-axis in bubble chart in Chartjs
- How to remove gridlines and grid labels in Chartjs Radar?
- How to feed hour and minute data into chartJS
- Chartjs Datasets overlapping and z-index
- Create a rounded bar graph with Angular and chartJS
- Displaying mixed types of legends (bar and lines) with Chartjs
- Chartjs not rendering chart and no error thrown
- Want to draw data using chartjs in django
- ChartJS Line chart cut off at the top and bottom
- How to get onClick Event for a Label in ChartJS and React?
- Update charts in chartjs and angular
- ChartJS click on bar and change it's background color
- unable to add background color to the canvas using jspdf and chartjs
- Chartjs adding icon to tooltip and label
- How to create dynamic charts with Django and Chart.js?
- Removing ChartJS 2 border and shadow from point style legend
- Make y-axis sticky when having horizontal scroll on chartJS and Angular
- ChartJs php array into 'labels' and 'datasets'
More Query from same tag
- Output array of hashes from Ruby on Rails to chart.js
- Angular Chart.js - Remove Moment.js as Dependency / Reduce Bundle Size
- Chart.js -> Displaying % on pie chart
- Chart.js not deploying properly on Heroku
- chart.js - Disable labels
- How to put images/ charts into table?
- How to add symbols in angular charts?
- how to set a custom tick format in chartjs options from laravel controller?
- Chart.js Bar Chart with a switch/radio button to group data / Troubleshooting bar color
- Chart.Js is keeping old data after AJAX call
- ReactJS Components Not loading unless you reload the site for the 2nd time
- Change legend position of ng-charts (using angular2)
- I want to draw a horizontal line
- Two independent time axes in Chart.js
- How to add space to the bottom of the chart in chartjs [angular]
- How to change chartjs ticks orientation to 'slope right'?
- Best way to connect Django Query results to Chart.js charts?
- charts.js add data with date
- Display JSON data in chartjs
- Puppeteer with Chart.js
- Chart.js chart.update() method is not doing anything
- Charts.js - Bar chart different colors for value intervals not working
- Reading converted rss to json file with chart.js not working
- Laravel passing orders to Chart.js
- Chart.js in a Vue page throws error: do not mutate vuex store state outside mutation handlers
- Chart.js: Create custom major ticks on log x-Axis?
- Grouped bar charts each group different level in chart.js
- Fully destroy charts on ngDestroy method from Angular 4
- Chart.register is not a function
- How can I get two stacked chart.js charts to be different types?