0

i want to automatic update a string/field of a simple webpage. The field is the latest date, which i get from this function:

def get_latest_date2():
    now = datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(seconds=20)
    now_string = now.isoformat()
    return str(now_string[:-14]) + '0Z'

So, when i run my django project the time appears on the webpage, but it does not update itself (which is totally normal). So i tried to use ajax to automatic refresh the time, but i'm not getting it from myself. I still don't understand how to make the js script update the time field automatically without a manual update (F5).

Here my codes, and something things that i tried.

forms.py

from .models import Book

class TimeForm(forms.ModelForm):
    class Meta:
        model = ExactTime
        fields = ('time')

models.py

from django.db import models

# Create your models here.
class ExactTime(models.Model):
    time = models.CharField(max_length=255)

views.py

from django.http import HttpResponse
from . import API_LOL_txt

def updatetime(request):
    response_dic={}
    form_template='dashboard/dashboard-home.html'
    if request.method == 'POST':
        time = TimeForm(request.POST)
        response_dic['time'] = time
        return render(request,'dashboard/dashboard-home.html', response_dic)

    response_dic['time'] = API_LOL_txt.get_latest_date2()
    return render(request,'dashboard/dashboard-home.html', response_dic)

base.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">

   <title>API LOL</title>
</head>
<body>

    {% block content %}
    {% endblock %}
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="{% static '/js/jquery.js' %}"></script>
    <script src="{% static '/js/update.js' %}"></script>

</body>
</html>

dashboard-home.html

{% extends 'dashboard/base.html' %}

{% block content %}
    <h3>Dashboard home</h3>
    <div id=update-time>
        <p>Time: {{ time }} </p>
    </div>        
{% endblock content %}

urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('', views.updatetime, name='dashboard-home'),
]

update.js

var refreshStream = function(){
    $.ajax({
        url: '/',
        method: 'GET',
        data: {},
        success: function(data){
            $('#update-time').replaceWith($('#update-time',data));
        },
    });
}

var total_seconds = 1;
setInterval(function(){
    refreshStream();
},total_second * 1000);

I'm trying to learn how to use django and ajax, so sorry if there is something very wrong in my code.

  • Please don't make regular Ajax requests just to update a timer - it's dead easy to handle this in just client-side Javascript, so you don't have to have all your users hitting your server every second! – Robin Zigmond Mar 01 '21 at 00:03
  • i know, but i wanna learn how to use, because i'll make a a webpage which needs update a lot of values in real time. Ty for your answer – gabriel figueiredo Mar 01 '21 at 00:18
  • @gabrielfigueiredo it looks good to me, cant really tell where it could be going wrong. I suggest adding some 'console.log()' cmds in the javascript function to check whether it is running periodically or not. you will then be able to tell the source of the error. – AzyCrw4282 Mar 01 '21 at 07:57
  • Does this answer your question? [Django CSRF check failing with an Ajax POST request](https://stackoverflow.com/questions/5100539/django-csrf-check-failing-with-an-ajax-post-request) – Ivan Starostin Mar 01 '21 at 09:41

0 Answers0