[Django]-How to implement countdown timer in django

3๐Ÿ‘

โœ…

You would definitely need some javascript to do the countdown timer. Like this one โ€“ http://keith-wood.name/countdown.html

Then any action that happens, you can do a basic ajax call to your django URL(view) to update any values in the db or anything else you need to do with the request.

When the countdown stops, you can probably record some time-left value into django and then when you need to continue the timer you can again do an ajax call to some view which will return you the time to start the countdown from and you can reconstruct your countdown timer with the time left.

๐Ÿ‘คzubinmehta

6๐Ÿ‘

model.py

class chek(models.Model):
    date = models.DateTimeField(auto_now_add=False, blank=True, null=True)

views.py

def jaya(request):
  ob=chek.objects.get(id=2)
  return render(request,'jaya.html',{'ob':ob})

use script like this

<script>
function makeTimer() {
   var endTime=new Date({{ ob.date|date:"U" }} * 1000);
    endTime = (Date.parse(endTime) / 1000);

        var now = new Date();
        now = (Date.parse(now) / 1000);

        var timeLeft = endTime - now;

        var days = Math.floor(timeLeft / 86400);
        var hours = Math.floor((timeLeft - (days * 86400)) / 3600);
        var minutes = Math.floor((timeLeft - (days * 86400) - (hours * 3600 )) / 60);
        var seconds = Math.floor((timeLeft - (days * 86400) - (hours * 3600) - (minutes * 60)));

        if (hours < "10") { hours = "0" + hours; }
        if (minutes < "10") { minutes = "0" + minutes; }
        if (seconds < "10") { seconds = "0" + seconds; }

        $("#days").html(days + "<span>Days</span>");
        $("#hours").html(hours + "<span>Hours</span>");
        $("#minutes").html(minutes + "<span>Minutes</span>");
        $("#seconds").html(seconds + "<span>Seconds</span>");

}

setInterval(function() { makeTimer(); }, 1000);
</script>

html body

<body class="game_info" data-spy="scroll" data-target=".header">

     <div class="col-md-6 col-sm-6 col-xs-12">
        <div class="row">
           <div class="full">
              <div class="right-match-time">
                 <h2>Next Match</h2>
                 <ul id="countdown-1" class="countdown">
                    <li><span id="days"></span>Day </li>
                    <li><span id="hours"></span>Hours </li>
                    <li><span id="minutes"></span>Minutes </li>
                    <li><span id="seconds"></span>Seconds </li>
                 </ul>

              </div>
           </div>
        </div>
     </div>
  </div>
๐Ÿ‘คMuhammad Shabin

Leave a comment