首页 > 解决方案 > DJango 的 HTML 表格中的标签是如何组织的?

问题描述

表倒置

我正在尝试组织一个 HTML 表格,但是我想要的行出现在相同的列中。他们是我应该用来解决这个问题的附加标签吗?

这是我的 html 代码和 django 模板标签..

<table>
  <thead> 
    <th>height</th>
    <th>birthday</th>
  </thead>                
  <tr>
    {% for ht in height  %}
      <td>{{ ht.heightft }}' {{ ht.remainingInches }}</td>
    {% endfor %}
  </tr>
  <tr>
    {% for b in bday  %}
      <td>{{ b.bday }}</td>
    {% endfor %}
  </tr>
</table>

视图.py

def displayVitals(request):
height = Height.objects.all()
bday = UserBDay.objects.all()

my_dict={'height':height, 'bday':bday}

return render(request, 'profiles_api/user_vitals.html', context=my_dict)

模型.py

class Height(models.Model):
userID = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
heightft = models.IntegerField()
remainingInches = models.IntegerField()

def __str__(self):
    return str(self.userID)

标签: djangodjango-templates

解决方案


由于您有两个以上的数据,因此您的数据会溢出图表,因为它的方向错误。不应该是:

| Height | Birthday |
|  5'6"  | 3/4/1999 |
|  6'4"  | 8/7/1996 |
        ...

如果是这样的话

def displayVitals(request):
    height = Height.objects.all()
    bday = UserBDay.objects.all()
    my_dict = {'data': zip(height, bday)}  # pairs data up
    return render(request, 'profiles_api/user_vitals.html', context=my_dict)
<table>
  <thead> 
    <th>height</th>
    <th>birthday</th>
  </thead>
  {% for height, bday in data %}
    <tr>
      <td>{{ d.height }}</td>
      <td>{{ d.bday }}</td>
    </tr>
  {% endfor %}
</table>

不过,您可能需要重新检查变量名称。


推荐阅读