使用实际数据时间和数据字段的生日在 Django 模板中定义年龄

Define age in django template using actual datatime and birthday with datafield

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

这是我的代码:

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:

{% 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