+ 9
Display a clock on my site(Python, Django)
I am currently learning django, and I am trying to make a simple app. I need to make a clock, I know for the time module, but it only shows the current time when I start the server, but I need a clock that is updating in real time so that I can call a function for example every day at 1pm. Can someone help me with that. Thanks
3 Antworten
+ 2
Try to consider how your app is constructed in the Django framework, from the user's perspective.
User -- Frontend -- Backend -- Server
The user interacts with a web browser to access your app. What they see is the html page, typically wrapped by a Django template - this is the Frontend. The page itself is generated by some python code, based on the Django view/model, in the "Backend", but only when the server receives a HTTP request. The html page itself can be considered as static content.
If you want a real-time clock on the result page, that assumes some dynamic content and you can typically achieve it best with some javascript. With javascript you may change parts of the html page on the client side, while the user is viewing it. If we stick to your scenario, for example every few seconds you may use javascript to call the server (=a django view) to retrieve the current time, and use it to update a part of the actual HTML page.
Without javascript I guess you would have to refresh the whole HTML page regularly. That will just recreate it using the Django code with the fresh time. If you want to display hours and minutes, actually you could get away with this method by refreshing every 60 seconds. But if you want to show seconds in real time, then this would not be feasible and you may be better off to code the whole thing in javascript.
+ 7
Thank you so much, you both gave me exactly what I needed! I wish you all the best and thank you for taking the time to give me the answer !
+ 2
The key javaScript function to look at is setInterval. Check out this YouTube vid on making a simple slide show:
https://www.youtube.com/watch?v=xbJ_BU8XnDw&t=4s
It changes the picture each second automatically. Give you any ideas? If this code can change the picture each second, it could also update the innerHTML on a DIV that shows the time, each second. For the most accuracy, you would want to query a web time server each seconds. You should also think about time zones. Any given person loading your pages might be in any given time zone, somewhere in the world.