2016-10-02 106 views
2

我想將「delta time」顯示爲「x天前」。我嘗試過Django的timesince過濾器,但它返回'x天,x分鐘'。我只想顯示幾天。我嘗試了人性化的自然時間,但我想它只適用於DateTimeField。我使用的是DateField。Django - 無法在模板中加載自定義過濾器

我有一個像這樣的自定義過濾器(app_filters.py);

from django import template 
from datetime import date 

register = template.Library() 


@register.filter(name='days_since') 
def days_since(value): 
    delta = value - date.today() 

    if delta.days == 0: 
     return 'Today' 
    elif delta.days < 1: 
     return '{} days ago'.format(abs(delta.days)) 
    elif delta.days == 1: 
     return 'Tomorrow' 
    elif delta.days > 1: 
     return 'In {} days'.format(delta.days) 

這是應用程序文件夾;

app/ 
    models.py 
    views.py 
    ... 
    templatetags/ 
     __init__.py 
     app_filters.py 

我加入了「應用」到INSTALLED_APPS settings.py中 我想在這樣的模板使用此過濾器;

{% extends 'app/base.html' %} 
{% load app_filters %} 

{{ entry.date_updated | days_since }} 

然後我得到錯誤:'app_filters'不是註冊的標籤庫。

我的錯誤在哪裏?

+0

可以加載從殼過濾器文件?在'python manage.py shell'中嘗試類似'from app.templatetags import app_filters'。也有可能在app_filters.py的某個地方出現錯誤,並且Django沒有把它傳遞給你。另外,請原諒明顯的問題,但您是否嘗試重新啓動服務器? – borfast

+0

'app_filters.py'沒有錯誤,我只是試了一下,它工作得很好。我確實遇到了與你一樣的錯誤,但在我的情況下,這是因爲我的'templatetags'文件夾位於錯誤的位置,因此即使該應用程序在「INSTALLED_APPS」中也沒有被拾取。這可能是你的情況嗎? – borfast

+0

嘗試在項目目錄中創建您的模板標籤文件夾。它將按預期工作。 – Aniket

回答

4

我意識到我需要重新啓動web服務器來加載自定義模板過濾器。這是這種情況下的解決方案。

0

我有一個類似的問題:以及重新啓動,以確保您的filters.py類在INSTALLED_APPS django否則他們將不會被拿起。

The app that contains the custom tags must be in INSTALLED_APPS in order for the {% load %} tag to work. This is a security feature: It allows you to host Python code for many template libraries on a single host machine without enabling access to all of them for every Django installation.

https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#howto-custom-template-tags