【问题标题】:how to get only the values of sqlite not the column name, then show them to the user in html?如何仅获取 sqlite 的值而不是列名,然后在 html 中将它们显示给用户?
【发布时间】:2020-04-09 18:09:11
【问题描述】:

我正在使用烧瓶制作一个简单的网络应用程序,用户可以在其中与其他用户分享他的食谱。

总而言之,您应该输入食谱的成分和步骤,然后将它们插入到sqlite数据库中,然后显示它们,这是我的问题,我得到了: https://i.stack.imgur.com/t7nGj.png

这绝对不是我想要的。

我只想获取没有列名 ('direction') 的值(制作汉堡的步骤),这是我的代码:

@app.route("/recipes")
@login_required

def recipes():

# gets all the recipes
recipes = db.execute("SELECT * FROM recipes;")

# list of all the direction, for each recipe
directions_list = []

# loops through directions table and gets each direction for each recipe
for recipe in recipes:
    dirs = {}
    directions = db.execute("select direction from directions where recipe_id = :recipe_id", recipe_id = recipe['id'])
    dirs = directions
    directions_list.append(dirs)

print(directions_list, file=sys.stderr)

return render_template("recipes.html", recipes = recipes, directions_list = directions_list)

这是我应该代表这些数据的 HTML 代码:

{% block main %}
<div class="card-deck">
  <div class="row row-cols-1 row-cols-md-2">
    {% for recipe in recipes %}
      <div class="col mb-3">
        <div class="card">
          <img src="..." class="card-img-top" alt="...">
          <div class="card-body">
            <h5 class="card-title">{{recipe['name']}}</h5>
            <p class="card-text">{{recipe['description']}}</p>
            <div class="row">
              <div class="col">
                Prep: {{recipe['prep']}}m
              </div>
              <div class="col">
                Cooking: {{recipe['cooking']}}m
              </div>
              <div class="col">
                Ready in: {{recipe['ready']}}m
              </div>
            </div>
            <ul>
              {% for direction in directions_list %}
              <li>{{directions_list[recipe['id']-1]['direction']}}</li>
              {% endfor %}
            </ul>
          </div>
        </div>
      </div>
    {% endfor %}
  </div>
</div>
{% endblock %}


is there any easier and better way to show those recipe steps? and maybe if I could list each of them as a bullet list element?


  [1]: https://i.stack.imgur.com/t7nGj.png

【问题讨论】:

标签: html sqlite web flask


【解决方案1】:

这个循环从不使用direction,这应该引起你的注意。

   {% for direction in directions_list %}
                  <li>{{directions_list[recipe['id']-1]['direction']}}</li>

但是它应该迭代什么?对应这个配方的不是directions_list的成员吗? (即recipe['id'] - 1)

在纯 python 中,这应该会给出想要的结果*

for recipe in recipes:
    for direction in directions_list[recipe['id'] - 1]:
        print(direction['direction'])

*建议的代码基于execute 方法返回字典列表的假设。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-20
    • 2016-04-08
    • 2015-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-08
    • 1970-01-01
    相关资源
    最近更新 更多