@orpha
To create dynamic charts with Django and Chart.js, follow these steps:
Here's an example code snippet to get you started:
views.py:
1 2 3 4 5 6 |
from django.shortcuts import render from .models import DataModel def chart_view(request): data = DataModel.objects.all() return render(request, 'chart_template.html', {'data': data}) |
chart_template.html:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
<!DOCTYPE html> <html> <head> <title>Dynamic Chart</title> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> </head> <body> <canvas id="myChart" width="400" height="400"></canvas> <script> var ctx = document.getElementById('myChart').getContext('2d'); var data = {{ data }}; var labels = data.map(item => item.label); var values = data.map(item => item.value); var myChart = new Chart(ctx, { type: 'bar', data: { labels: labels, datasets: [{ label: 'Data', data: values, backgroundColor: 'rgba(255, 99, 132, 0.2)', borderColor: 'rgba(255, 99, 132, 1)', borderWidth: 1 }] }, }); </script> </body> </html> |
Make sure to replace 'DataModel' with the name of your model and 'label' and 'value' with the fields in your model that you want to display in the chart.
That's it! You should now have a dynamic chart in your Django app using Chart.js.