英文:
Is it possible to make a real-time clock with Django?
问题
views.py 中的代码获取当前时间。
from datetime import datetime
from django.shortcuts import render
def clock(request):
now = datetime.now()
context = {
'current_time': now.strftime('%Y-%m-%d %H:%M:%S')
}
return render(request, 'clock.html', context)
clock.html 中的代码显示当前时间。
{% extends "base.html" %}
{% block content %}
<h1>当前时间:</h1>
<p>{{ current_time }}</p>
{% endblock %}
英文:
I know that Django have a function that can get current time. However, it cannot continuously updates the time to the user interface (Real-time clock).
The code for getting the current time.
views.py
from datetime import datetime
from django.shortcuts import render
def clock(request):
now = datetime.now()
context = {
'current_time': now.strftime('%Y-%m-%d %H:%M:%S')
}
return render(request, 'clock.html', context)
clock.html
{% extends "base.html" %}
{% block content %}
<h1>Current Time:</h1>
<p>{{ current_time }}</p>
{% endblock %}
答案1
得分: 2
我的解决方案
time.js
function updateServerTime() {
$.getJSON('/server-time/', function(data) {
$('#server-time').text(data.server_time);
});
}
$(document).ready(function() {
updateServerTime();
setInterval(updateServerTime, 1000);
});
views.py
def server_time(request):
now = datetime.now()
response_data = {'server_time': now.strftime('%Y-%m-%d %H:%M:%S')}
return JsonResponse(response_data)
urls.py
path('server-time/', views.server_time, name="server_time"),
time.html
<div class="time">
<span id="server-time"></span>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="{% static 'js/time.js' %}"></script>
英文:
MY SOLUTION
time.js
function updateServerTime() {
$.getJSON('/server-time/', function(data) {
$('#server-time').text(data.server_time);
});
}
$(document).ready(function() {
updateServerTime();
setInterval(updateServerTime, 1000);
});
views.py
def server_time(request):
now = datetime.now()
response_data = {'server_time': now.strftime('%Y-%m-%d %H:%M:%S')}
return JsonResponse(response_data)
urls.py
path('server-time/',views.server_time,name="server_time"),
time.html
<div class="time">
<span id="server-time"></span>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="{% static 'js/time.js' %}"></script>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论