【问题标题】:HTML table not fetching data from Django only showing headingHTML表格不从Django获取数据只显示标题
【发布时间】:2021-08-03 19:05:30
【问题描述】:

我将 HTML、CSS 和 Javascript 用于前端,Django 用于后端,PostgresSQL 用于 DB。实际上,我已经成功地将 EXCEL 文件中的数据加载到 Django,并且我正在尝试将 数据从 Django 获取到 HTML Table。但是,我只得到表的标题,而不是数据。如何解决。

index.html

{%extends "base.html"%}
{%block content%}

<html>
<table>
  <thead>
      <th>Brand</th>
      <th>Name</th>
  </thead>
  <tbody>
    <tr> 
      <td><strong>{{pro.brand}}</strong></td>
      <td><strong>{{pro.name}}</strong></td>
      </tr>
  </tbody> 
</table>
{%endblock%}

views.py

def product(request):
    pro = Product.objects.all()
    return render(request, 'index.html',{'pro': pro})

urls.py(应用文件)

urlpatterns = [
    path('product/', views.product, name='product'),
]

【问题讨论】:

    标签: html css django django-models django-templates


    【解决方案1】:

    因为你的上下文变量 pro 是一个查询集(一个实例列表),你必须像这样在模板中做一个循环:

    {%extends "base.html"%}
    {%block content%}
    
    <html>
    <table>
      <thead>
          <th>Brand</th>
          <th>Name</th>
      </thead>
      <tbody>
        {% for p in pro %}
        <tr> 
          <td><strong>{{p.brand}}</strong></td>
          <td><strong>{{p.name}}</strong></td>
        </tr>
        {% endfor %}
      </tbody> 
    </table>
    {%endblock%}
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-11
      • 2022-01-23
      • 2018-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多