【问题标题】:How are tags organized in HTML Table in DJango?DJango 的 HTML 表格中的标签是如何组织的?
【发布时间】:2020-07-27 00:23:00
【问题描述】:

我正在尝试组织一个 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>

view.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)

models.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)

【问题讨论】:

  • heightbday 是如何生成的?通常你会生成并循环遍历一个迭代,其中每个元素都包含一行的所有数据
  • height 和 bday 是我的 models.py 中的两个类。
  • 添加您的模型和视图
  • 添加了我的视图和模型代码。 @IainShelvington
  • 您还没有添加UserBDay 模型,但我认为它还有一个指向UserProfile 的外键?您可能应该使用UserProfile 查询集来生成表行。目前尚不清楚您为什么要按照最初的方式对行进行分组,因为您没有以任何方式对它们进行分组

标签: django django-templates


【解决方案1】:

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

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

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

【讨论】:

  • 感谢@crimsonpython24 这个解决方案有效。感谢您向我展示 Zip 功能。
猜你喜欢
  • 1970-01-01
  • 2021-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多