欢迎访问宙启技术站
智能推送

Django中使用humanize模板标签在模板中显示相对时间

发布时间:2024-01-08 06:00:00

在Django中,我们可以使用humanize模板标签来在模板中显示相对时间,例如将时间格式化为"2 days ago"、"3 hours ago"等。

首先,确保在Django项目中已经安装了django.contrib.humanize应用程序,并将其添加到项目的INSTALLED_APPS中。

在需要使用humanize模板标签的模板中,可以通过在模板的开头添加{% load humanize %}来加载humanize模板标签。

下面是一个使用humanize模板标签的例子:

{% load humanize %}

<p>发布时间:{{ post.published_at|naturaltime }}</p>
<p>最后更新时间:{{ post.updated_at|naturaltime }}</p>

上面的例子中,post.published_atpost.updated_at是DateTimeField类型的字段,在模板中使用naturaltime过滤器来将时间值格式化为相对时间。

naturaltime过滤器会将时间值转换为相对于当前时间的表示,例如"2 days ago"、"3 hours ago"等。

请注意,要使用naturaltime过滤器,需要确保设置了合适的时区,可以在Django的settings.py中进行配置。例如,可以使用TIME_ZONE = 'Asia/Shanghai'来设置时区为上海。

希望以上例子能够帮助你理解如何在Django中使用humanize模板标签来显示相对时间。