2016-08-19 13 views
0

更新模板中變量值的選項(最佳方法)是什麼?模板中的django更新時間變量

模板:

<div class="time-container"> 
    {{ time }} 
</div> 

觀點:

def index(request): 
    now = datetime.now() 
    context = { 
     'time': now, 
    } 
    return render(request, 'times/index.html', context) 

我想顯示的實際時間(Django的情況下從NTP同步)每秒更新一次。我應該使用websockets嗎?

+1

一個很容易的解決方案可能只是做Javascript和更新的時間,而不是擔心它是一個變量。不知道這是否是你的選擇。 –

+0

不幸的不是。我想從後臺計算機顯示一個精確的時間,它將從ntp同步。 –

回答

1

使用JavaScript。下面是使用jQueryMoment.js一個例子:

<!-- this div will contain time --> 
<div class="time-container"></div> 

... 

<!-- include required js libraries --> 
<script src="path/to/jquery.js"></script> 
<script src="path/to/moment.js"></script> 

<!-- now the actual js code to show time --> 
<script> 
    function updateTime(){ 
     $('.time-container').html(moment().format('h:mm:ss')); 
    }; 

    updateTime(); 

    setInterval(function(){ 
     updateTime(); 
    },1000); 
</script> 
+0

感謝您的快速響應,但我想從後端(ntp同步)顯示時間而不是從前端/客戶端。 –