How to display “x days ago” type time using Humanize in Django template?

大城市里の小女人 提交于 2019-11-28 06:58:06
Bernhard Vallant

Django has a built-in template filter timesince that offers the same output you mentioned above. The following filter just strips the second part after the comma:

from datetime import datetime, timedelta
from django import template
from django.utils.timesince import timesince

register = template.Library()

@register.filter
def age(value):
    now = datetime.now()
    try:
        difference = now - value
    except:
        return value

    if difference <= timedelta(minutes=1):
        return 'just now'
    return '%(time)s ago' % {'time': timesince(value).split(', ')[0]}

You should duplicate your django.contrib.humanize.templatetags.humanize.py to myapp.templatetags.myhumanize and modify it to your needs. (I can't find the actual line that returns "x days, y hours ago". Which version of django/humanize are you using?)

You can also now use an ExpressionWrapper or Case/When that will utilize the queryset and database to format it directly.

Example output, in combo with day/days pluralized off the top of my head:

overdue = ExpressionWrapper(timezone.now() - F('due_date'), output_field=fields.DurationField())
objects = Activity.objects.all().order_by('-due_date').annotate(overdue=overdue)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!