久久久久久AV无码免费看大片,亚洲一区精品人人爽人人躁,国产成人片无码免费爱线观看,亚洲AV成人无码精品网站,为什么晚上搞的时候要盖被子

django模板通過自定義過濾器格式化時(shí)間戳

時(shí)間:2022-03-31 22:16:20 類型:python
字號:    

django模板不能寫py代碼,那么怎么把世間戳轉(zhuǎn)換成日期時(shí)間格式呢,我們可以通過django提供的自定義過濾器功能來實(shí)現(xiàn)

1、在應(yīng)用目錄下創(chuàng)建 templatetags 目錄(與 templates 目錄同級,目錄名只能是 templatetags)。

2、在 templatetags 目錄下創(chuàng)建任意 py 文件,如:my_tags.py。

3、my_tags.py 文件代碼如下:

from django import template
import time

register = template.Library()   #register的名字是固定的,不可改變


@register.filter
# 格式化時(shí)間戳
def formTime(t,f):
    return time.strftime(f, time.localtime(float(t)))

修改 settings.py 文件的 TEMPLATES 選項(xiàng)配置,添加 libraries 配置:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')]
        ,
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
            "libraries":{                          # 添加這邊三行配置
                'my_tags':'templatetags.my_tags'   # 添加這邊三行配置
            }                                      # 添加這邊三行配置
        },
    },
]

4、在使用自定義標(biāo)簽和過濾器前,要在 html 文件 body 的最上方中導(dǎo)入該 py 文件。

   {% load my_tags %}

5, 模板中使用

 

{{ row.addtime | formTime:"%Y-%m-%d %H:%M:%S"}}


<