Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 formatted as "HH:MM" -- It is always less than 24. So, I tried these in the HTML template file:

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

However, all I get is an empty space.

What am I doing wrong?

like image 389
Sardathrion - against SE abuse Avatar asked Mar 17 '16 10:03

Sardathrion - against SE abuse


People also ask

What is DurationField?

DurationField is used for storing python datetime. timedelta instance in the database. One can store any type of duration based on time or date in the database. To know more about datetime. timedelta, check out Python | datetime.

What is a model Django?

A model is the single, definitive source of information about your data. It contains the essential fields and behaviors of the data you're storing. Generally, each model maps to a single database table. The basics: Each model is a Python class that subclasses django.db.models.Model .


2 Answers

A timedelta instance is not a time or a datetime. Therefore it does not make sense to use the time or date filters.

Django does not come with any template filters to display timedeltas, so you can either write your own, or look for an external app that provides them. You might find the template filters in django-timedelta-field useful.

like image 154
Alasdair Avatar answered Nov 09 '22 00:11

Alasdair


For posterity: here is what I used in the end. This is the content 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 this:

{% load datetime_filter %}
[...]
{{ slice.day0|format_datetime }}
like image 25
Sardathrion - against SE abuse Avatar answered Nov 08 '22 23:11

Sardathrion - against SE abuse