DurationField Format

I have a DurationField defined in my model as

 day0 = models.DurationField('Duration for Monday', default=datetime.timedelta) 

When I try to view this, I want it to be formatted as "HH: MM" - it is always less than 24. So, I tried them in the HTML template file:

 {{ slice.day0|time:'H:M' }} {{ slice.day0|date:'H:M' }} 

However, all I get is empty space.

What am I doing wrong?

+5
source share
2 answers

A timedelta instance is not time or datetime . Therefore, it makes no sense to use time or date filters.

Django does not use template filters to display timedeltas, so you can either write your own or search for an external application that provides them. You can find template filters in django-timedelta-field .

+6
source

For posterity: this is what I used at the end. This is the contents of <app>/templatetags/datetime_filter.py :

 # -*- coding: utf-8 -*- """Application filter for `datetime`_ 24 hours. .. _datetime: https://docs.python.org/2/library/datetime.html """ from django import template from datetime import date, timedelta register = template.Library() @register.filter(name='format_datetime') def format_datetime(value): hours, rem = divmod(value.seconds, 3600) minutes, seconds = divmod(rem, 60) return '{}h {}m'.format(hours, minutes) 

Then in the view add the following:

 {% load datetime_filter %} [...] {{ slice.day0|format_datetime }} 
+3
source

Source: https://habr.com/ru/post/1245223/


All Articles