可以使用Django制作实时时钟吗?

huangapple go评论58阅读模式
英文:

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 = {
        &#39;current_time&#39;: now.strftime(&#39;%Y-%m-%d %H:%M:%S&#39;)
    }
    return render(request, &#39;clock.html&#39;, context)

clock.html

{% extends &quot;base.html&quot; %}

{% block content %}
    &lt;h1&gt;Current Time:&lt;/h1&gt;
    &lt;p&gt;{{ current_time }}&lt;/p&gt;
{% 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(&#39;/server-time/&#39;, function(data) {
      $(&#39;#server-time&#39;).text(data.server_time);
    });
  }
  
  $(document).ready(function() {
    updateServerTime();
    setInterval(updateServerTime, 1000);
  });

views.py

def server_time(request):
    now = datetime.now()
    response_data = {&#39;server_time&#39;: now.strftime(&#39;%Y-%m-%d %H:%M:%S&#39;)}
    return JsonResponse(response_data)

urls.py

path(&#39;server-time/&#39;,views.server_time,name=&quot;server_time&quot;),

time.html

&lt;div class=&quot;time&quot;&gt;
    &lt;span id=&quot;server-time&quot;&gt;&lt;/span&gt;
&lt;/div&gt;
&lt;script src=&quot;https://code.jquery.com/jquery-3.6.0.min.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;{% static &#39;js/time.js&#39; %}&quot;&gt;&lt;/script&gt;

huangapple
  • 本文由 发表于 2023年4月10日 21:55:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/75977734.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定