Flask+Python:点击按钮后如何展示数据库信息卡片
解决方法
1. 修正后端代码(传递描述信息到模板)
你的后端代码里查询到desc后没有传递给模板,而且数据库查询结果需要正确提取,修改如下:
@app.route("/factpage", methods=["GET","POST"]) def enterfruit(): if request.method == "POST": fruit = request.form.get("fruitname") username = session["username"] db.execute("insert into fruits(username, fruit) values (?,?)", username, fruit) # 获取查询结果,fetchone()返回单条记录,无结果则返回None desc_result = db.execute("select description from fruitinfo where fruit=?", fruit).fetchone() # 提取描述内容,处理查询不到的情况 desc = desc_result["description"] if desc_result else "暂无该水果的描述信息" flash("Thank you for entering " + fruit + "!") # 将desc传递给模板 return render_template("factpage.html", desc=desc) else: # GET请求时传递空值,避免模板报错 return render_template("factpage.html", desc=None)
2. 调整前端模板(条件显示卡片并固定到底部)
修改模板代码,添加判断确保只有有描述时才显示卡片,同时调整布局让卡片固定在页面底部:
{% block content %} <!-- 原有页面内容区域 --> <!-- 底部描述卡片 --> {% if desc %} <div class="fixed-bottom mb-3"> <div class="container"> <div class="card"> <div class="card-header"> 水果描述 </div> <div class="card-body"> <blockquote class="blockquote mb-0"> <p>{{ desc }}</p> </blockquote> </div> </div> </div> </div> {% endif %} {% endblock content %}
关键说明
- 后端必须通过
render_template的参数把desc传递给模板,模板才能读取到该变量。 - 使用
fetchone()从数据库游标中获取实际查询结果,否则desc只是游标对象,无法直接显示内容。 - 添加
{% if desc %}判断,避免页面加载时显示空卡片;Bootstrap的fixed-bottom类可让卡片固定在页面底部,mb-3增加外边距避免被浏览器状态栏遮挡。
内容的提问来源于stack exchange,提问作者rookie654
相关产品推荐
相关产品推荐

