2017-08-01 29 views
0

代码:Django的 - 只获得今年以来我的工作日期

#models.py 
class Profile(models.Model): 
    date_of_birth = models.DateField(null=True, blank=True) 

#template.html 
<span>Age: <small>{{ object.date_of_birth|timesince }}</small></span> 

该代码给了我,例如:25岁3个月。我应该怎样做才能让我只有几年? (在这种情况下25)任何想法?谢谢。

+0

请参阅本https://momentjs.com/ –

+0

你可以写一个摆脱的自定义模板标签剩下的部分'timesince(date_time).split(',')[0]' –

回答

1

在您的班级中添加一项功能,仅返回出生年份以下我已添加get_birth_year函数仅返回年份。

from datetime import datetime 

class Profile(models.Model): 
    date_of_birth = models.DateField(null=True, blank=True) 

    def get_birth_year(self): 
     return datetime.now().year - self.date_of_birth.year 

现在,您可以访问get_birth年仅模板获得的出生年份

#template.html 
<span>Age: <small>{{ object.get_birth_year }}</small></span> 
+0

我不确定这个函数是否会在每种情况下都返回我有效的年份,但我认为现在是最好的解决方案。 – Barburka