You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask中Jinja2无法通过字段名渲染表格数据的问题求助

问题解决方法

1. 解决字段名无法访问的问题

你当前用fetchall()获取的是元组列表,元组仅支持索引访问,因此row['style_ID']无法生效。只需将查询结果转换为可按字段名访问的格式,有两种常用实现方式:

方法一:使用字典游标(推荐)

修改数据库连接配置,让游标直接返回可按字段名访问的对象:

@app.route("/register_style")   
def style_list():
    BASE_DIR = os.path.dirname(os.path.abspath(__file__))
    SQLPATH = os.path.join(BASE_DIR,'DatBaseTexCO.db' )
    conn = db.connect(SQLPATH)
    # 配置游标返回支持字段名访问的对象(sqlite3需提前导入from sqlite3 import Row)
    conn.row_factory = db.Row
    curs = conn.cursor()
    Query = ("SELECT style_ID,styleNo,styleName,styleYarn,styleLabel,styleType FROM style_table")
    curs.execute(Query)    
    rows = curs.fetchall()
    print(rows)
    return render_template("newstyle.html", rows=rows)

修改后前端{{row['style_ID']}}即可正常渲染数据。

方法二:手动转换为字典列表

若不想修改游标配置,可在获取数据后手动将元组转成字典:

@app.route("/register_style")   
def style_list():
    BASE_DIR = os.path.dirname(os.path.abspath(__file__))
    SQLPATH = os.path.join(BASE_DIR,'DatBaseTexCO.db' )
    conn = db.connect(SQLPATH)
    curs = conn.cursor()
    Query = ("SELECT style_ID,styleNo,styleName,styleYarn,styleLabel,styleType FROM style_table")
    curs.execute(Query)    
    # 获取查询的字段名列表
    columns = [desc[0] for desc in curs.description]
    # 将每行元组与字段名配对成字典
    rows = [dict(zip(columns, row)) for row in curs.fetchall()]
    print(rows)
    return render_template("newstyle.html", rows=rows)

2. 添加基于ID的DELETE/UPDATE按钮

第一步:后端新增对应路由

添加接收style_ID参数的删除、更新路由,处理业务逻辑:

from flask import redirect, url_for

@app.route('/delete_style/<int:style_id>', methods=['POST'])
def delete_style(style_id):
    BASE_DIR = os.path.dirname(os.path.abspath(__file__))
    SQLPATH = os.path.join(BASE_DIR,'DatBaseTexCO.db' )
    conn = db.connect(SQLPATH)
    curs = conn.cursor()
    # 执行删除操作,用参数化查询避免SQL注入
    curs.execute("DELETE FROM style_table WHERE style_ID = ?", (style_id,))
    conn.commit()
    conn.close()
    # 删除后重定向回列表页
    return redirect(url_for('style_list'))

@app.route('/update_style/<int:style_id>')
def update_style(style_id):
    # 查询要修改的记录并渲染更新页面
    BASE_DIR = os.path.dirname(os.path.abspath(__file__))
    SQLPATH = os.path.join(BASE_DIR,'DatBaseTexCO.db' )
    conn = db.connect(SQLPATH)
    conn.row_factory = db.Row
    curs = conn.cursor()
    curs.execute("SELECT * FROM style_table WHERE style_ID = ?", (style_id,))
    style = curs.fetchone()
    conn.close()
    return render_template('update_style.html', style=style)

第二步:前端模板添加操作按钮

在表格每行末尾新增操作列,嵌入修改、删除按钮:

<tbody>                
    {% for row in rows %}                                   
    <tr>
        <td>{{row['style_ID']}}</td>
        <td>{{row['styleNo']}}</td>
        <td>{{row['styleName']}}</td>
        <td>{{row['styleYarn']}}</td>
        <td>{{row['styleLabel']}}</td>
        <td>{{row['styleType']}}</td>
        <!-- 操作按钮列 -->
        <td>
            <a href="{{ url_for('update_style', style_id=row['style_ID']) }}" class="btn btn-primary">修改</a>
            <form action="{{ url_for('delete_style', style_id=row['style_ID']) }}" method="POST" style="display: inline;">
                <button type="submit" class="btn btn-danger" onclick="return confirm('确定要删除这条记录吗?')">删除</button>
            </form>
        </td>             
    </tr>                       
    {% endfor %}             
</tbody>

内容的提问来源于stack exchange,提问作者Mevlut Ademay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 00:25:31