使用实际的数据时间和生日以及数据字段在Django模板中定义年龄 [英] Define age in django template using actual datatime and birthday with datafield
本文介绍了使用实际的数据时间和生日以及数据字段在Django模板中定义年龄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是django的初学者,并试图显示我的用户群中每个用户的年龄.
i'm begginer at django and trying to display age for every user in my base of users.
这是我的代码:
models.py:
models.py:
class Cv(models.Model):
author = models.ForeignKey('auth.User')
name = models.CharField(max_length=25, null = True)
surname = models.CharField(max_length=25, null = True)
address = models.CharField(max_length=100, blank=True)
telephone = models.IntegerField()
birth_date = models.DateField(blank=True, null=True)
email = models.EmailField(max_length=50, null=True)
skills = models.TextField(null=True)
specialization = models.CharField(max_length=30, blank=True, null=True)
interests = models.TextField(blank=True, null=True)
summary = models.TextField(blank=True, null=True)
thumbnail = models.FileField(upload_to=get_upload_file_name, blank=True)
def zapisz(self):
self.save()
def __str__(self):
return self.surname
template.html:
template.html:
{% block base %}
<div class="vvv">
<h2>Base of users</h2><hr>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Nr.</th>
<th>Full Name</th>
<th>Specialization</th>
<th>Age</th>
<th>E-mail</th>
</tr>
</thead>
<tbody>
{% for cv in cvs %}
<tr>
<td>{{forloop.counter}}.</td>
<td><a href="{% url "proj.views.cv_detail" pk=cv.pk %}">{{cv.name}} {{cv.surname}}</a></td>
<td>{{cv.specialization}}</td>
<td>{{ cv.age }} </td>
<td>{{cv.email}}</td>
</tr>
{% endfor %}
</tbody>
</table><br>
</div>
{% endblock %}
views.py:
@login_required
def base_cv(request):
cvs = Cv.objects.filter()
for cv in cvs:
def calculate_age(self):
import datetime
return int((datetime.datetime.now() - cv.birth_date).days / 365.25 )
age = property(calculate_age)
con = {
'cvs': cvs,
'age': age,
}
return render(request, 'base_cv.html', con)
不知道为什么渲染和显示后的字段为空.
And don't know why the fields after rendering and displaying, are empty.
感谢您的帮助!
推荐答案
calculate_age
应该是模型上的函数.您可以使用此处所述的 @property
装饰器,例如:
calculate_age
should be a function on the model. You can use the @property
decorator described here like:
from datetime import datetime
class Cv(models.Model):
...
@property
def age(self):
return int((datetime.now().date() - self.birth_date).days / 365.25)
那么您的视图就可以是:
Then your view can simply be:
@login_required
def base_cv(request):
con = {'cvs': Cv.objects.all()}
return render(request, 'base_cv.html', con)
与 filter
全部>当您需要所有模型时.
all is preferred over filter
when you want all of the models.
这篇关于使用实际的数据时间和生日以及数据字段在Django模板中定义年龄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文