0

please excuse me in advance in case that my question has been answered many times before. Cause I'm new to django, I just don't have a clue which keyword I have to search with.

I made a countdown timer which works well in the console. The function display a clock(remaining days:hours:mins:secs) decrementing a sec until the end.

def countdown():

dt = get_delta()

while dt > 0:

d = calculation(dt)['day']
h = calculation(dt)['hour']
m = calculation(dt)['min']
s = calculation(dt)['sec']

countdown.timer = '{:02d} days {:02d} hours {:02d} mins {:02d} secs'.format(d, h, m, s)
print(countdown.timer, end='\r')
time.sleep(1)
dt -= 1
countdown.boom = "--------Happy birthday!--------"
print(countdown.boom)

What I want to do is to render this part on my webpage built by django.

countdown.timer = '{:02d} days {:02d} hours {:02d} mins {:02d} secs'.format(d, h, m, s)

This is my render function part:

def index(request):

context = {'timer': countdown.timer}

return render(request, 'MainApp/index.html', context)

I tried to pass countdown.timer variable or countdown() function itself to my django template.

<div class="container-fluid" style="background-color: black">
        <div class="rows">
            <div class="col-md-12">
                <article>
                    <h1>This is where my timer is.</h1>
                    <p>{{ timer }}</p> 
                </article>
            </div>
        </div>
        
    </div>

It doesn't feel right and it didn't work but I don't know how to get it done. When I run its dev server, the function works nicely on the console but it doesn't render anything on the browser. Could you please tell me what I should dig?

1 Answers1

0

That's not how the backend and frontend works, you must call the backend before you can receive a data from it, but in your code yes it will display using this <p>{{ timer }}</p> but it will only display the initial data, the timer will not count down, what you have to do is to create a query on the backend to get the date where to end the timer which i think is the birthdate then pass it to the frontend using this var bdate = "{{birthdate}}";, then create a script using javascript or jquery or whatever you want to use to create a countdown timer which ends with the variable bdate. see this post - How to write a countdown timer in JavaScript?

romel rada
  • 21
  • 4
  • Thank you romel, in fact I found something called Pyscript and hope it would help me out but seemingly it doesn't get along with django... yet. I think I should rewrite my app with javascript again as your advice. Thanks again! – Lee Soyon Aug 13 '22 at 14:55