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?
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.
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 .
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.
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 }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With