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

Flask HTML模板中如何在文本框旁显示函数返回的已有值

在Flask模板中显示后端传递的默认值到输入框

嘿,这事儿其实挺简单的!咱们只需要两步:后端把默认值传到模板,然后前端模板用Jinja2语法把值绑定到输入框的value属性就行。我帮你修改一下你的代码,你一看就懂了。

第一步:修改后端代码,传递默认值到模板

首先,你需要在渲染template1.html的路由里,把Value1的已有值作为参数传给render_template。比如假设你从某个地方(比如数据库、配置或者直接定义)拿到了Value1的默认值,咱们以直接定义为例修改result1路由:

from flask import Flask, render_template, request

app = Flask(__name__)
import logging

@app.route("/")
def hello():
    return "Hello csdfwe!"

@app.route('/test/')
def check():
    return render_template('template.html')

@app.route('/result/', methods = ['GET', 'POST'])
def result():
    # 注意:Python3里print需要加括号,这里帮你修正了
    print("*****", request.form, "******")
    return render_template('template1.html')

@app.route('/result1/', methods = ['GET', 'POST'])
def result1():
    # 这里模拟从后端获取Value1的已有值,你可以换成实际的数据源(比如数据库查询)
    existing_value1 = "这是Value1的已有值"
    # 把值传给模板,参数名可以自定义,比如叫default_value1
    return render_template('template1.html', default_value1=existing_value1)

if __name__ == "__main__":
    app.run(debug=True)  # 加上debug=True方便开发时调试

第二步:修改前端模板,绑定默认值到输入框

然后修改template1.html里的Value1输入框,给它加上value属性,用Jinja2的变量语法把后端传过来的值填进去:

<html>
<body>
<form action = "{{ url_for('result') }}" method = "POST">
    <p>Value1 <input type = "text" name = "Value1" value="{{ default_value1 }}" /></p>
    <p>Value2<input type ="text" name = "Value2" /></p>
    <p>Charging Duration <input type ="text" name = "Charging_Duration" /></p>
    <p><input type = "submit" value = "submit" name = "submit" /></p>
</form>
</body>
</html>

原理说明

  • Flask用的Jinja2模板引擎会自动把{{ default_value1 }}替换成后端render_template里传递的实际值,这样输入框加载时就会显示这个已有值。
  • 用户可以直接在输入框里修改这个值,提交表单后,新的值会通过request.form['Value1']在后端result路由里获取到,完全不影响正常的表单提交逻辑。

另外提个小细节:你原来的代码里print语句没有加括号,这在Python3里会报错,我已经帮你修正了,加上debug=True也能让开发时更方便调试~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:13:51