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

同一路由下提交一个表单时如何避免清空另一个表单的字段?

解决同路由下多表单提交后主表单数据丢失问题

问题核心

提交「Add Experience」表单时,主表单「Employee Form」的输入会被清空,本质原因是每次请求都会重新实例化EmployeeInfo表单,没有保留用户之前的输入数据。

最优解决方案:使用Flask Session临时存储主表单数据

利用Flask的session临时保存主表单的输入内容,提交小表单后从session恢复数据到主表单,避免重复填写。这种方案比cookie更安全(数据存于服务器端,默认带签名防篡改),且适配50+字段的复杂表单场景。

修改后的app.py代码

from flask import Flask, render_template, request, session
from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField, validators
from wtforms.validators import InputRequired

app = Flask(__name__)
app.config['SECRET_KEY'] = 'Thisisasecret'
# 可选:设置session有效期,默认浏览器关闭后失效
app.config['PERMANENT_SESSION_LIFETIME'] = 3600  # 1小时

class EmployeeInfo(FlaskForm):
    fullName = StringField('Full Name',[validators.InputRequired()])
    dept = StringField('Department',[validators.InputRequired()])

class CompanyDetails(FlaskForm):
    yearsOfExp = IntegerField('Year of Experience',[validators.InputRequired()]) 

def custom_function(val):
    print(f"This employee has {val} years of experience.")

@app.route('/', methods = ['GET','POST'] )
def index():
    companydetails = CompanyDetails()
    employeeInfo = EmployeeInfo()

    # 从session恢复主表单数据(首次加载或提交小表单后)
    if 'employee_data' in session:
        employeeInfo.fullName.data = session['employee_data']['fullName']
        employeeInfo.dept.data = session['employee_data']['dept']

    if request.method == "POST" and employeeInfo.validate_on_submit():
        # 提交主表单时,将数据存入session(后续若需编辑可保留)
        session['employee_data'] = {
            'fullName': employeeInfo.fullName.data,
            'dept': employeeInfo.dept.data
        }
        return render_template('showData.html', form1=employeeInfo) 

    if request.method == "POST" and companydetails.validate_on_submit():
        val = request.form["yearsOfExp"]
        custom_function(val)
        # 提交小表单时,保存当前主表单的输入到session
        session['employee_data'] = {
            'fullName': request.form.get('fullName', ''),
            'dept': request.form.get('dept', '')
        }
        # 将session数据赋值回表单,确保渲染时显示
        employeeInfo.fullName.data = session['employee_data']['fullName']
        employeeInfo.dept.data = session['employee_data']['dept']

    return render_template('index.html',form1 = employeeInfo, form = companydetails)

if __name__ == '__main__':
    app.run(debug= True, port=5000)

优化提示

若主表单包含50+字段,可通过遍历表单字段批量存入session,避免逐个赋值:

# 批量保存主表单数据到session
session['employee_data'] = {field.name: request.form.get(field.name, '') for field in employeeInfo}
# 批量恢复数据
for field in employeeInfo:
    field.data = session['employee_data'].get(field.name, '')

备选方案:隐藏字段传递主表单数据

若不想依赖session,可在小表单中添加主表单所有字段的隐藏输入,提交小表单时一并传递主表单数据。适合字段较少的场景,50+字段时维护成本较高。

修改后的index.html小表单部分

<h4>Add Experience</h4>
<form method="POST" action="{{url_for('index')}}">
    {{ form.csrf_token }}
    {{ form.yearsOfExp.label }} {{ form.yearsOfExp }}
    <!-- 添加主表单字段的隐藏输入 -->
    <input type="hidden" name="fullName" value="{{ form1.fullName.data or '' }}">
    <input type="hidden" name="dept" value="{{ form1.dept.data or '' }}">
    <input type="submit" value="Submit">
</form>

修改app.py的小表单处理逻辑

if request.method == "POST" and companydetails.validate_on_submit():
    val = request.form["yearsOfExp"]
    custom_function(val)
    # 从请求中获取主表单数据并赋值
    employeeInfo.fullName.data = request.form.get('fullName', '')
    employeeInfo.dept.data = request.form.get('dept', '')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 09:29:55