Format of timesince filter

后端 未结 3 1381
你的背包
你的背包 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: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.

提交回复
热议问题