如何为HTML表格每行添加按钮并将首列月份值传入Flask函数进行查询
我来帮你一步步解决这个问题——核心问题在于你没把选中的月份参数传递给详情页面的查询逻辑,同时详情页的SQL也没做针对性过滤。咱们分三步修改:
1. 调整主页面HTML,传递月份参数
原来的跳转链接是固定的,需要把当前行的月份作为查询参数带过去。用Flask的url_for生成正确的路由链接,同时把每行第一列的月份值传进去:
<table width=80%> <!-- Show Report Table --> <thead> <tr> {% for header in headings %} <th>{{ header }}</th> {% endfor %} <th>操作</th> <!-- 新增表头让结构更清晰 --> </tr> </thead> <tbody> {% for row in data %} <tr> {% for cell in row %} <td>{{ cell }}</td> {% endfor %} <td class="td-actions text-right"> <!-- 用url_for生成带月份参数的跳转链接,row[0]就是当前行的月份 --> <a href="{{ url_for('monthly_sales_table_sub', month=row[0]) }}" style="padding: 4px 12px; background: #007bff; color: white; border-radius: 4px; text-decoration: none;"> more details </a> </td> </tr> {% endfor %} </tbody> </table>
这里把原来的input改成了样式化的a标签,更符合GET请求的跳转场景,也避免了不必要的表单提交逻辑。
2. 修改Flask详情路由,接收并传递月份参数
在详情页的路由里,需要获取URL中携带的月份参数,再把它传给SQL查询函数:
from flask import request # 别忘了导入request模块 @api.route('/monthly_sales_report_sub', methods=['GET']) def monthly_sales_table_sub(): # 从URL查询字符串中获取选中的月份 selected_month = request.args.get('month') if not selected_month: # 处理没有传参数的异常情况,比如返回提示或跳回主页面 return "请选择一个月份查看详情", 400 # 调用SQL函数时传入选中的月份 report_data = SQL_Operations.get_monthly_sales_report_sub(connection, selected_month) return render_template("monthly_sales_report_sub.html", headings=report_data['headings'], data=report_data['rows'])
3. 更新SQL查询函数,添加月份过滤逻辑
修改get_monthly_sales_report_sub函数,让它接收月份参数,并在SQL语句中添加WHERE条件做过滤,同时用参数化查询避免SQL注入风险:
def get_monthly_sales_report_sub(connection, month): cursor = connection.cursor() # 添加WHERE子句过滤指定月份,用%s作为参数占位符(如果是SQLite数据库,替换成?即可) query = ("""SELECT month, sales_person, total_num_sold, total_sales FROM Sale WHERE month = %s;""") # 执行查询时传入month参数,参数化查询是安全的写法 cursor.execute(query, (month,)) res = [] for (month, sales_person, total_num_sold, total_sales) in cursor: res.append([month, sales_person, total_num_sold, total_sales]) res_new = dict() res_new['headings'] = ['month', 'sales_person', 'total_num_sold', 'total_sales'] res_new['rows'] = res return res_new
最后确认详情页HTML
确保monthly_sales_report_sub.html的表格渲染逻辑正确,它会自动使用传入的data(仅选中月份的记录):
<table width=80%> <thead> <tr> {% for header in headings %} <th>{{ header }}</th> {% endfor %} </tr> </thead> <tbody> {% for row in data %} <tr> {% for cell in row %} <td>{{ cell }}</td> {% endfor %} </tr> {% endfor %} </tbody> </table>
这样修改后,点击某行的more details按钮,就会把对应月份传给Flask,查询该月份的专属数据并在详情页展示了。
内容的提问来源于stack exchange,提问作者codebeginner
相关产品推荐
相关产品推荐

