Home > Software engineering >  Is there a way to automatically update a webpage using Django?
Is there a way to automatically update a webpage using Django?

Time:12-28

I am trying to create a countdown timer into a webpage using Django. I made the requisite time calculations in the view for the template, and passed them in as context to the template, and displayed it using the context. However, the timer only updates as I refresh the webpage. Is there any way I can have the timer auto-update?

View Function for template:

def home(request):
    #Time Calculations Performed Here
    time_dict={'days': days, 'hours': hours, 'minutes': minutes, 'seconds': seconds}

    context={'participants':participants, 'time':time_dict}
    return render(request, 'base/home.html', context)

Template Section Where Timer is Displayed:

<hr>
<h3>Countdown Timer</h3>
<div><h5>
    Days: {{time.days}}, Hours: {{time.hours}}, Minutes: {{time.minutes}}, Seconds: {{time.seconds}}
<h5></div>
<hr>

CodePudding user response:

You can use jQuery ajax here something like this:

views.py

from django.http import JsonResponse

def cal_time(request):
    #Time Calculations Performed Here
    time_dict={'days': days, 'hours': hours, 'minutes': minutes, 'seconds': seconds}
    return JsonResponse(timde_dict)

home.html

<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.min.js">
</script>
<script>
  function getUpdatedTime(){
     $.ajax({url: "/cal_time/", success: function(result){
         var content = "Days: " result['days'] ", Hours: " result['hours'] ", Minutes: " result['minutes'] ", Seconds: " result['seconds'];
         $("h5").text(content);
         setTimeout(function(){getUpdatedTime();}, 2000); // will call function to update time every 2 seconds
     }});
  }
  $(document).ready(function(){
     getUpdatedTime();
  });
</script>
  • Related