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.