Format of timesince filter

后端 未结 3 1378
你的背包
你的背包 2021-02-02 01:04

Is there a way to use the {{date|timesince}} filter, but instead of having two adjacent units, only display one?

For example, my template is currently displ

相关标签:
3条回答
  • 2021-02-02 01:40

    A quick and dirty way:

    Change the django source file $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  
    
    0 讨论(0)
  • 2021-02-02 01:52

    I can't think of a simple builtin way to do this. Here's a custom filter I've sometimes found useful:

    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
    

    Then you could just do

    {{ date|timesince|upto:',' }}
    
    0 讨论(0)
  • 2021-02-02 01:54

    Since the timesince filter doesn't accept any arguments, you will have to manually strip off the hours from your date.

    Here is a custom template filter you can use to strip off the minutes, seconds, and microseconds from your datetime object:

    #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)
    

    If you haven't used a custom template filter or tag before, you will need to create a directory in your django application (i.e. at the same level as models.py and views.py) called templatetags, and create a file inside it called __init__.py (this makes a standard python module).

    Then, create a python source file inside it, for example my_tags.py, and paste the sample code above into it. Inside your view, use {% load my_tags %} to get Django to load your tags, and then you can use the above filter as shown in the documentation above.

    0 讨论(0)
提交回复
热议问题