1

I'm trying to use different stylesheet in django template if the time since publish is less than 15 minutes. I created the DateTimeField in my model that adds 15 minutes with time delta

blink = models.DateTimeField(default=datetime.datetime.now()+datetime.timedelta(minutes=15))

In the view.py I have defined dayandtime

dayandtime = datetime.datetime.now()

In the template I have this if statement

{% if mi.blink > dayandtime %}
...
{% else %}
...

Unfortunately it goes to else even though the mi.blink is greater than dayandtime.

I tried to use answer from this question [question]: DateTime compare in django template

{% if mi.blink.date < dayandtime.date and mi.blink.time < dayandtime.time %}

but it's still not working. Is it because the timedelta has been added?

Community
  • 1
  • 1
hplodur
  • 111
  • 3
  • 16

1 Answers1

1

You can't do that in your model field definition. If you do the timedelta in the definition, it will be only be called ONLY ONCE when your django project initializes, then the value will be reinitialized the next time you restart the service, same thing with datetime.now().

You can however call the datetime.now without the parenthesis. This way you pass the now() function as a function callback, so it's called every time the field default is accessed:

blink = models.DateTimeField(default=datetime.datetime.now)

Thus if you want to add 15 minutes, just create another function:

def get_time():
    return datetime.datetime.now() + datetime.timedelta(minutes=15)

# your field would accept function callback
blink = models.DateTimeField(default=get_time)
Shang Wang
  • 24,909
  • 20
  • 73
  • 94