【问题标题】:Formatting a table via SQL database in Flask通过 Flask 中的 SQL 数据库格式化表格
【发布时间】:2016-07-27 08:54:28
【问题描述】:

我的 Flask 应用程序存在轻微的 HTML 格式问题。我正在尝试在表格中显示我在法庭案件中拥有的一些数据列表,该表格的标题为Full Name, Type of Appeal Filed, County。但是,我无法弄清楚如何正确组合 HTML 语法和 Flask 语法,以便让表格以我想要的方式显示。这是我的views.py

from flask import render_template, flash, redirect, g
from app import app
from .models import Individual_Criminal
from .forms import LoginForm

@app.route('/')
@app.route('/index')
def index():
    user = [i for i in Individual_Criminal.query.order_by('type_of_appeal desc').all()]
    return render_template('index.html',
                           title='Home',
                           user=user)

index.html:

<!-- extend base layout -->
{% extends "base.html" %}

{% block content %}
    <p>
      <table class="table table-striped">
      <thead>
      <tr>
      <th>Full Name</th>
      <th>Type of Appeal</th>
      <th>County</th>
      </tr>
      </thead>
      <tbody>
      <tr>
    {% for u in user %}
      <td>{{ u.full_name }}</td>
      <td>{{ u.type_of_appeal}}</td>
      <td> {{ u.county }}</td>
      </tr>
      </tbody>
      </table>
    </p>
    {% endfor %}
{% endblock %}

到目前为止我所做的尝试: 我已经在index.html 文件上尝试了许多变体,因为我非常肯定这就是它出错的地方。最初我在{% for u in user %} 块中有all 的内容,但这导致每次创建表时每次只有一个条目,如下所示:

所以,那是错误的。然后,我尝试将 &lt;tbody&gt; 行移到 for 循环上方,所以 index.html 看起来像这样:

<!-- extend base layout -->
{% extends "base.html" %}

{% block content %}
    <p>
      <table class="table table-striped">
      <thead>
      <tr>
      <th>Full Name</th>
      <th>Type of Appeal</th>
      <th>County</th>
      </tr>
      </thead>
      <tbody>
    {% for u in user %}
      <tr>
      <td>{{ u.full_name }}</td>
      <td>{{ u.type_of_appeal}}</td>
      <td> {{ u.county }}</td>
      </tr>
      </tbody>
      </table>
    </p>
    {% endfor %}
{% endblock %}

产生了这样的东西:

所以,还是错了。我的 expected output 是一个类似于尝试 no1 的表格,除了包含所有信息的 一个 表格。非常感谢任何帮助!

【问题讨论】:

  • 您的视图中不需要列表理解。只需将.all() 的返回值赋值给users。这样你只迭代一次结果。

标签: python html python-2.7 flask


【解决方案1】:

根据 html 表的构造方式(一个 tbody 和多个 trs 包含固定数量的 tds)进行猜测:

    {% for u in user %}
      <tr>
      <td>{{ u.full_name }}</td>
      <td>{{ u.type_of_appeal}}</td>
      <td> {{ u.county }}</td>
      </tr>
    {% endfor %}
      </tbody>
      </table>
    </p>

{% endblock %}

【讨论】:

  • 完美!只要它允许,我就会接受它作为答案。非常感谢@jDo!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-04-14
  • 1970-01-01
  • 2011-09-09
  • 2022-01-15
  • 2019-11-18
  • 2013-10-31
  • 1970-01-01
相关资源
最近更新 更多