Use Django 3.2 timesince depth parameter for child age

This commit is contained in:
Christopher C. Wells 2021-04-11 13:00:17 -07:00
parent fe92d3ea17
commit e27f7b76a0
3 changed files with 13 additions and 19 deletions

View File

@ -1,5 +1,7 @@
# -*- coding: utf-8 -*-
from django import template
from django.utils import timesince, timezone
from django.utils.translation import gettext as _
from core import utils
@ -10,14 +12,17 @@ register = template.Library()
@register.filter
def child_age_string(birth_date):
"""
Format a Child's age with monkey-patched timesince.
Format a Child's age with a timeunit depth of 1.
:param birth_date: datetime instance
:return: a string representation of time since `birth_date`.
"""
if not birth_date:
return ''
# Return "0 days" for anything under one day.
elif timezone.localdate() - birth_date < timezone.timedelta(days=1):
return _('0 days')
try:
return utils.child_age_string(birth_date)
return timesince.timesince(birth_date, depth=1)
except (ValueError, TypeError):
return ''

View File

@ -18,9 +18,13 @@ class TemplateTagsTestCase(TestCase):
def test_child_age_string(self):
date = timezone.localdate() - timezone.timedelta(days=0, hours=6)
self.assertEqual('0\xa0days', duration.child_age_string(date))
self.assertEqual('0 days', duration.child_age_string(date))
date = timezone.localdate() - timezone.timedelta(days=1, hours=6)
self.assertEqual('1\xa0day', duration.child_age_string(date))
date = timezone.localdate() - timezone.timedelta(days=45)
self.assertEqual('1\xa0month', duration.child_age_string(date))
date = timezone.localdate() - timezone.timedelta(days=95)
self.assertEqual('3\xa0months', duration.child_age_string(date))
def test_duration_duration_string(self):
delta = timezone.timedelta(hours=1, minutes=30, seconds=15)

View File

@ -1,23 +1,8 @@
# -*- coding: utf-8 -*-
from django.utils import timesince, timezone
from django.utils import timezone
from django.utils.translation import ngettext
def child_age_string(duration):
"""Monkey patch timesince function to day precision only.
"""
default_timesine_chunks = timesince.TIMESINCE_CHUNKS
timesince.TIMESINCE_CHUNKS = (
(60 * 60 * 24 * 365, 'year'),
(60 * 60 * 24 * 30, 'month'),
(60 * 60 * 24 * 7, 'week'),
(60 * 60 * 24, 'day'),
)
ts = timesince.timesince(duration)
timesince.TIMESINCE_CHUNKS = default_timesine_chunks
return ts
def duration_string(duration, precision='s'):
"""Format hours, minutes and seconds as a human-friendly string (e.g. "2
hours, 25 minutes, 31 seconds") with precision to h = hours, m = minutes or