[Chartjs]-Want to draw data using chartjs in django

3👍

View should be like this:

def get_temperature_show(request):

data = Temper.objects.all()
return render(request,'weather/showtemper.html',{'data':data})

In the template just iterate the data. Code is as follows:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
    {#        labels: ['M', 'T', 'W', 'T', 'F', 'S', 'S'],#}

    labels: [{% for d in data %} "{{ d.date }}", {% endfor %}],
    datasets: [{
        label: 'Sensor 1',
        {#            data: [12, 19, 3, 17, 6, 3, 7],#}
        data: [{% for temp in data %} "{{ temp.sensor1_temp }}", {% endfor %}],
        backgroundColor: "rgba(153,255,51,0.4)"
    }, {
        label: 'Sensor 2',
        data: [{% for temp in data %} "{{ temp.sensor2_temp }}", {% endfor %}],
        backgroundColor: "rgba(255,153,0,0.4)"
    },
        {
            label: 'Sensor 3',
            data: [{% for temp in data %} "{{ temp.sensor3_temp }}", {% endfor %}],
            backgroundColor: "rgba(0,0,255,0.4)"
        },
        {
            label: 'Sensor 4',
            data: [{% for temp in data %} "{{ temp.sensor4_temp }}", {% endfor %}],
            backgroundColor: "rgba(255,0,0,0.4)"
        }]
}
});

1👍

from json import JSONEncoder
class MyEncoder(JSONEncoder):
   def default(self, o):
       if isinstance( o, datetime.datetime):
           return o.isoformat()
       return o 


json.dumps(cls=MyEncoder)

try this when you are dumping in your django code

Leave a comment