Why does my time countdown return NaN when i format time in django template

Viewed 64

I have been working on this app where i have a time countdown to event date, having a challenge working around the time format in django when i format the start datetime in django format{{ event.start|date:'D d M Y' }}" it return NaN in template, but when i format datetime like this "date: 2021-11-11T08:32:06+11:11" it works, I have search on here for a solution, but somehow the solution didn't work in my case.

HTML 
#This works 
<div class="items-center space-x-2 text-center grid grid-cols-4" uk-countdown="date: 2021-11-11T08:32:06+11:11">
<div class="bg-gray-100 rounded-md p-2 border shadow-inner">
                    <div class="uk-countdown-days text-lg font-bold"></div>
                    <div class="text-xs">DAYS </div>
                </div>
                <div class="bg-gray-100 rounded-md p-2 border shadow-inner">
                    <div class="uk-countdown-hours text-lg font-bold"></div>
                    <div class="text-xs">HOURS </div>
                </div>
                <div class="bg-gray-100 rounded-md p-2 border shadow-inner">
                    <div class="uk-countdown-minutes text-lg font-bold"></div>
                    <div class="text-xs">MIN  </div>
                </div>
                <div class="bg-gray-100 rounded-md p-2 border shadow-inner">
                    <div class=" uk-countdown-seconds text-lg font-bold"></div>
                    <div class="text-xs">SEC </div>
                </div>
            </div>

#but this does not work, It returns NaN
<div class="items-center space-x-2 text-center grid grid-cols-4" uk-countdown="{{ event.start|date:'D d M Y' }}"">

Here is my model for event

class Event(models.Model):
   
    start = models.DateTimeField(_('start'),db_index=True,default=datetime.now().replace(microsecond=0))
    end = models.DateTimeField(_('end'), db_index=True,default=datetime.now().replace(microsecond=0))

My view for event

def event_main(request,pk):
    event = get_object_or_404(Event, pk=pk)
    ctx = {'event':event}
    return render(request,'event/event_main.html',ctx)
1 Answers

The formats are completely different... In the first example, the value is presented in ISO format

uk-countdown="date: 2021-11-11T08:32:06+11:11"

in the second, you're formatting it

uk-countdown="{{ event.start|date:'D d M Y' }}""

which would give you

uk-countdown="Fri 11 Nov 2021""

you should probably use

uk-countdown="date: {{ event.start|date:"c" }}"

Note that I've added the date: prefix and removed the second " as well.

You also have an issue with your model defaults. This:

start = models.DateTimeField(_('start'),db_index=True,default=datetime.now().replace(microsecond=0))
end = models.DateTimeField(_('end'), db_index=True,default=datetime.now().replace(microsecond=0))

will give you the time the module is imported, which in production can be days before your model is saved...

Related