BRHSM
BRHSM

Reputation: 884

Customize updated|timesince in a django template

I've a django template which displays the last time an element was updated in a database like this:

<small>updated {{ updated|timesince }} ago</small>

where updated is the timestamp of the last update of that element.

I, however, don't like thw way it is displaying this information. For example if i's just updated it sais: 'updated 0 minutes ago' which looks kinda wierd. I would like it to say something like: 'updated just now'

So I wrote this piece of code to try to make that happen:

{% if is_updated%}
     {% if updated|timesince == '0 minutes' %}
         <small>updated just now </small>
     {% else %}
         <small>updated {{ updated|timesince }} ago</small>
     {% endif %}
 {% endif %}

here is_updated is a context variable set like this:

if element.updated != element.uploaded:
    is_updated = True

however it's always showing me 'updated X minutes ago' even if the element hasn't been updated. What could I be doing wrong?

Model for the element:

title       = models.CharField(max_length=120)
identifier  = models.SlugField(blank=True, null=True)
category    = models.CharField(max_length=120, default="uncategorized")
description_short = models.CharField(max_length=300, default="none")
description = models.TextField(default="none")
uploaded    = models.DateTimeField(auto_now_add=True)
updated     = models.DateTimeField(auto_now=True)
time        = models.IntegerField()

Upvotes: 0

Views: 688

Answers (1)

user2390182
user2390182

Reputation: 73498

Even if an instance is only once created and never touched again, the two auto_add and auto_add_now DateTimeFields can hold slightly different timestamps. If you check it in the shell, you will see sth like:

>>> element.uploaded
datetime.datetime(2018, 1, 4, 14, 7, 37, 542192, tzinfo=<UTC>)
>>> element.updated
datetime.datetime(2018, 1, 4, 14, 7, 37, 542213, tzinfo=<UTC>)

You notice the difference in the microseconds. You should check their equality with a little epsilon:

if (element.updated - element.uploaded).microseconds > 500:
    is_updated = True

timesince does not support time deltas under a minute. From the docs:

Minutes is the smallest unit used, and “0 minutes” will be returned for any date that is in the future relative to the comparison point.

All you can do is feed the extra information into the context:

# view
recent = (element.updated - element.uploaded).seconds < 60

# template
{% if recent %}
     <small>updated just now </small>
 {% else %}
     <small>updated {{ updated|timesince }} ago</small>
 {% endif %}

Upvotes: 1

Related Questions