Django 3 template date tag return nothing

Viewed 125

I'm try to use date template tag to format datetime from database

2020-10-23 08:59:44.792274

on django template

{{ item.payment_received_time }} # return 2020-10-23 08:59:44.792274
{{ item.payment_received_time|date:"D d M Y" }} # return nothing

but nothing is returned, what am I missing on it ? Thanks

1 Answers

(…) but nothing is returned.

The |date template filter [Django-doc] only works on date and datetime objects. It can not process strings, since then the structure is "lost".

For example:

>>> Template('{{ foo|date:"D d M Y" }}').render(Context({'foo': datetime.now().date()}))
'Sun 25 Oct 2020'
>>> Template('{{ foo|date:"D d M Y" }}').render(Context({'foo': '2020-10-25'}))

In your models, you thus store the payment_received_time as a DateTimeField [Django-doc] or a DateField [Django-doc]:

class Payment(models.Model):
    payment_received_time = models.DateTimeField()
Related