3

我是 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 %}

视图.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)

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

谢谢你的帮助!

4

1 回答 1

4

calculate_age应该是模型上的一个函数。您可以使用此处@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)

filter当你想要所有模型时,all是首选。

于 2016-02-22T22:02:30.787 回答