【问题标题】:Format of timesince filter时间过滤器的格式
【发布时间】:2011-06-26 02:29:25
【问题描述】:

有没有办法使用{{date|timesince}}过滤器,但不是有两个相邻的单元,而是只显示一个?

例如,我的模板当前显示“18 小时 16 分钟”。如何让它显示“18 小时”? (此处不考虑四舍五入。)谢谢。

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    我想不出一个简单的内置方法来做到这一点。这是我有时发现有用的自定义过滤器:

    from django import template
    from django.template.defaultfilters import stringfilter
    
    register = template.Library()
    
    @register.filter
    @stringfilter
    def upto(value, delimiter=None):
        return value.split(delimiter)[0]
    upto.is_safe = True
    

    那你就可以了

    {{ date|timesince|upto:',' }}
    

    【讨论】:

    • 似乎delimiter 不应该是可选参数。你不妨给它一个合理的默认值,比如','。
    • @AndrewB。 split 的默认行为是在空格上拆分,并且在传递 None 时执行相同的操作
    • 啊,有道理。谢谢。
    【解决方案2】:

    由于timesince 过滤器不接受任何参数,因此您必须手动删除日期中的小时数。

    这是一个custom template filter,您可以使用它从您的日期时间对象中去除分钟、秒和微秒:

    #this should be at the top of your custom template tags file
    from django.template import Library, Node, TemplateSyntaxError
    register = Library()
    
    #custom template filter - place this in your custom template tags file
    @register.filter
    def only_hours(value):
        """
        Filter - removes the minutes, seconds, and milliseconds from a datetime
    
        Example usage in template:
    
        {{ my_datetime|only_hours|timesince }}
    
        This would show the hours in my_datetime without showing the minutes or seconds.
        """
        #replace returns a new object instead of modifying in place
        return value.replace(minute=0, second=0, microsecond=0)
    

    如果您之前没有使用过自定义模板过滤器或标签,则需要在您的 django 应用程序中创建一个名为 templatetags 的目录(即与 models.py 和 views.py 处于同一级别),并创建里面有一个名为 __init__.py 的文件(这是一个标准的 Python 模块)。

    然后,在其中创建一个 python 源文件,例如my_tags.py,并将上面的示例代码粘贴到其中。在您的视图中,使用 {% load my_tags %} 让 Django 加载您的标签,然后您可以使用上面文档中显示的上述过滤器。

    【讨论】:

      【解决方案3】:

      一种快速而肮脏的方式:

      更改 django 源文件 $PYTHON_PATH/django/utils/timesince.py @line51(django1.7) :

      result = avoid_wrapping(name % count)
      return result  #add this line let timesince return here
      if i + 1 < len(TIMESINCE_CHUNKS):
          # Now get the second item
          seconds2, name2 = TIMESINCE_CHUNKS[i + 1]
          count2 = (since - (seconds * count)) // seconds2
          if count2 != 0:
              result += ugettext(', ') + avoid_wrapping(name2 % count2)
      return result  
      

      【讨论】:

      • 最好只是复制它并制作自己的版本,速度稍慢但不那么脏。
      猜你喜欢
      • 2014-05-04
      • 2018-03-03
      • 2018-06-28
      • 2015-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多