3

Please excuse my newbie status to python and web applications.
For a few hours, I simply cannot get this to work properly.
All I want to do, is have the table items display the time with seconds.
It prints correctly from within views.py, but seems to undergo some conversion when passed to index.html(as seen on console.log)? Or is someone could clarify for me? or point me in the right direction please?

model.py:

    class dbMachine100RunTime(models.Model):
        ID = models.AutoField(primary_key=True)
        Machine = models.ForeignKey(Machines, on_delete=models.SET_NULL, null=True, blank=True)
        Date = models.DateField(auto_now=False, default=datetime.now)
        Time = models.TimeField(auto_now=False, default=datetime.now)
        OnOff = models.CharField(max_length=3, default="Error", null=True)
        Count = models.IntegerField(default=0, null=True)
    
        def __str__(self):
            return str(self.Machine)

views.py:

def index(request):
    EndTime = datetime.now()
    TimeDifference = timedelta(hours=1)
    StartTime = EndTime-TimeDifference

    MachineRuntime = dbMachine100RunTime.objects.filter(Time__range=(StartTime, EndTime))
    Machine = MachineRuntime[0].Machine

    print(MachineRuntime[0].Date) #Shows date as = 2021-04-25
    print(MachineRuntime[0].Time) #Shows time as = 10:30:36

    return render(request, 'Machine_Monitor/index.html', {'MachineRuntime': MachineRuntime, 'Machine': Machine})

index:

{% for item in MachineRuntime %}
          <tr>
            <td>{{item.Date}}</td>
            <td><time step="1">{{item.Time}}</time></td>
            <script>
               console.log("{{item.Date}}"); <!--Shows as: April 25, 2021 -->
               console.log("{{item.Time}}"); <!--Shows as: 10:30 a.m. -->
            </script>
          </tr>
         {% endfor %}
Clauds
  • 31
  • 1
  • look at template filter "time" https://docs.djangoproject.com/en/3.2/ref/templates/builtins/#time – OlegТ Apr 25 '21 at 09:55
  • Potentially in this instance you would benefit from the use of a DurationField https://docs.djangoproject.com/en/3.2/ref/models/fields/#durationfield – Lewis Apr 25 '21 at 10:01
  • Thank you, that was surprisingly easy once I knew where to look – Clauds Apr 29 '21 at 08:07

1 Answers1

0

In your case this would become:

{{ item.Time|time:"H:i:s" }}
pypie
  • 71
  • 6