Search code examples
pythonhtmlcssdjangoreal-time

Is it possible to make a real-time clock with Django?


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 %}

Solution

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