2015-01-26 2 views
0

으로하여 DateField를 필터링 내가 사용 장고 1.5.8장고 : 템플릿

내가 코드를 다음과 같이 템플릿에 Datefield 유형의 데이터를 필터링하고 싶습니다.

  • 는 장고의에 의해 {% if article.created >= (now - 7 days) %}을 처리 할 수있는 솔루션이 있습니까
  • 오래된 기사 date 형식

some_template.html

{% for article in articles %} 

    {# recent articles #} 
    {% if article.created >= (now - 7 days) %} 
     {{ article.created|timesince }} 

    {# old articles more than one week past #} 
    {% else %} 
     {{ article.created|date:"m d" }} 
    {% endif %} 

{% endfor %} 

로 표현 최근 기사 timesince 형식으로 표현 자신의 템플릿 태그?

또는 새 맞춤 필터를 만들어야합니까?

답변

2

사용자 지정 템플릿 태그를 사용하여이 작업을 수행 할 수도 있지만 모델 코드에서이 테스트를 구현하는 것이 훨씬 쉽습니다. 예를 들어 :

from datetime import date, timedelta 
class Article(models.Model): 
    [...] 
    def is_recent(self): 
     return self.created >= date.today() - timedelta(days=7) 

그런 다음 템플릿은 다음과 같습니다

{% for article in articles %} 
    {% if article.is_recent %} 
    {{ article.created|timesince }} 
    {% else %} 
    {{ article.created|date:"m d" }} 
    {% endif %} 
{% endfor %}