gpt4 book ai didi

python - 使用实际数据时间和生日以及数据字段在 django 模板中定义年龄

转载 作者:太空宇宙 更新时间:2023-11-03 16:54:18 24 4
gpt4 key购买 nike

我是 django 的初学者,试图显示我的用户群中每个用户的年龄。

这是我的代码:

模型.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

模板.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)

并且不知道为什么渲染和显示后字段为空。

感谢您的帮助!

最佳答案

calculate_age 应该是模型上的函数。您可以使用 here 描述的 @property 装饰器喜欢:

from datetime import datetime

class Cv(models.Model):

...

@property
def age(self):
return int((datetime.now().date() - self.birth_date).days / 365.25)

那么你的观点可以简单地是:

@login_required
def base_cv(request):
con = {'cvs': Cv.objects.all()}
return render(request, 'base_cv.html', con)

all当您需要所有模型时,优先于filter

关于python - 使用实际数据时间和生日以及数据字段在 django 模板中定义年龄,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35564664/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com