有没有办法使用 Django 自动更新网页?

Is there a way to automatically update a webpage using Django?

我正在尝试使用 Django 在网页中创建倒数计时器。我在模板的视图中进行了必要的时间计算,并将它们作为上下文传递给模板,并使用上下文显示它。但是,计时器仅在我刷新网页时更新。有什么方法可以让定时器自动更新吗?

查看模板函数:

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)

显示计时器的模板部分:

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

你可以在这里使用 jQuery ajax 这样的东西:

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>