1

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 %}
lilsnow02
  • 89
  • 7
  • 1
    You should make a view that respons with a JSON blob for example, and then let an AJAX call repeatedly make calls to update the content. JavaScript of course also can achieve the time, but that is the time of the client, and likely you want to display the "server" time. – Willem Van Onsem Apr 10 '23 at 13:56

1 Answers1

1

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>
lilsnow02
  • 89
  • 7