开发者

Define and insert age in django template

I have a model, view and template:

model

class Peoples(models.Model):
    l_name = models.CharField(max_length=50)
    f_name = models.CharField(max_length=50)
    m_name = models.CharField(max_length=50)
    tab_number = models.CharField(max_length=5)
    birthday = models.DateField(null=True, blank=True)
    post = models.CharField(max_length=250, blank=True)
    workpla开发者_运维知识库ce = models.ForeignKey(Workplace, null=True, blank=True)
    skill = models.CharField(max_length=20, blank=True)
    dopuska = models.TextField(blank=True)
    srok_dopuskov = models.DateField(null=True, blank=True)
    photo = models.ImageField(upload_to='img',blank=True)
    class Meta:
        ordering = ('l_name',)
    def __unicode__(self):
        return self.l_name
    def age(self):
        import datetime
        return int((datetime.datetime.now() - self.birthday).days / 365.25  )
    age = property(age)

view

def view_persone(request, tab_number):
    return direct_to_template(request, 'person.html', {
       'persone': Peoples.objects.filter(tab_number=tab_number),
    })

template

{% for person in persone %}
    Возраст: <b>{{ person.age }}</b>
{% endfor %}

But the field in template where should be an age is empty. why?


You need to do

 def age(self):
        import datetime
        return int((datetime.date.today() - self.birthday).days / 365.25  )

as your birthday is a DateField.


I think you first defined a method age and in the next line reassigned the name age. Try

def calculate_age(self):
    import datetime
    return int((datetime.datetime.now() - self.birthday).days / 365.25  )
age = property(calculate_age)

Aside: You can (and should) post the relevant portions of the code here and not expect the others to look up your code on a different site.


it will display the age based on your month too.

in models.py

class Profile(models.Model):
     date_of_birth = models.DateField()

     def age(self):
            import datetime
            dob = self.date_of_birth
            tod = datetime.date.today()
            my_age = (tod.year - dob.year) - int((tod.month, tod.day) < (dob.month, dob.day))
            return my_age

in profile.html

<span>Age : </span> <i> {{ profile.age }} </i>


You don't need a model method to calculate age; you can just use the built-in template filter timesince [link to doc]:

<span>Age: {{ person.age|timesince }}</span>

A downside is that it seems there is currently no way to customize the resulting string if you only want the age in years. For instance, it usually returns the month in addition to years, e.g. “37 years, 2 months”. It can also return strange strings like “65 years, 12 months” (when a birth date is not at least exactly 66 years ago). This filter is not specifically intended for computing a person's age after all.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜