Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

363
Visualizações
Want to draw data using chartjs in django

My application will take data using form and save it to the database and then draw it using chartjs . I have tried this code but gives me an error. My code is as follows :

def get_temperature_show(request):
all_temperatures = Temper.objects.all()

dates_label = []
sensor1_temp = []
sensor2_temp = []
sensor3_temp = []
sensor4_temp = []

for model in all_temperatures:
    dates_label.append(model.date)
    sensor1_temp.append(model.sensor1_temp)
    sensor2_temp.append(model.sensor2_temp)
    sensor3_temp.append(model.sensor3_temp)
    sensor4_temp.append(model.sensor4_temp)

data = {
    'dates': dates_label,
    'sensor1': sensor1_temp,
    'sensor2': sensor2_temp,
    'sensor3': sensor3_temp,
    'sensor4': sensor4_temp
}

return render(request, 'weather/showtemper.html', json.dumps({"data":data}))

But it gives the following-

datetime.date(2017, 4, 4) is not JSON serializable

My template example is like this:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: ['M', 'T', 'W', 'T', 'F', 'S', 'S'],
        datasets: [{
            label: 'apples',
            data: [12, 19, 3, 17, 6, 3, 7],
            backgroundColor: "rgba(153,255,51,0.4)"
        }, {
            label: 'oranges',
            data: [2, 29, 5, 5, 2, 3, 10],
            backgroundColor: "rgba(255,153,0,0.4)"
        }]
    }
});

Please help me to resolve this error

Thanks in advance

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

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)"
        }]
}
});
over 4 years ago · Santiago Trujillo Relatório

0

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

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda