Search code examples
javascriptjquerydjangobootstrap-4refresh

How to refresh a datetime tag every second in a Django Template?


I use Django 3 + Bootstrap 4 + MySQL 5.7 on a Laragon server, all on Windows 10.

I have a view with a variable dt_now = timezone.now() displayed in a Template with a simple <p>{{ dt_now }}</p> tag. I want to refresh this tag every second automatically without reloading all the htlm page. Is there a simple way to do that with Django or Bootstrap ? Or maybe should I prefer to use a jQuery methode ? At last, should I write a custom function ?


Solution

  • In JS without any framework:

    setInterval(function() {
      const currentTime = new Date();
      document.getElementById('currentTime').innerHTML = currentTime;
    }, 1000);
    <p id="currentTime"><p>