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

Dash Plotly代码中action路由'/charts/{x}'无法获取input1输入值问题

Dash Plotly Form路由传参问题解决方案

问题根源

  1. 你原有写法中html.Form的action属性在服务端首次渲染页面布局时就已经通过f-string完成了值计算,后续用户在前端输入input1的内容不会动态更新该属性,因此无法将用户输入的参数带入路由。
  2. 不推荐使用全局变量存储单用户输入值:Dash默认单进程多线程处理请求,所有用户共享服务端全局变量,会出现不同用户输入值互相覆盖的异常。
  3. 原有代码中html.Div的子组件没有包裹在列表内,会触发参数错误。

方案1:动态更新Form的action属性

给Form组件添加id,通过回调监听提交按钮点击事件,动态修改action属性即可实现需求:

app.layout = html.Div([
    dcc.Graph(
        id='example-graph',
        figure = fig,
    ),
    # 给Form添加id,移除初始写死的action
    html.Form(id='submit-form',
        children=[
            dcc.Input(id='input1', name='name'),
            html.Button('Submit', id='submit', type='submit'),
        ], 
        method="POST"
    )
])

@app.callback(
    Output("submit-form", "action"),
    Input('submit', 'n_clicks'),
    State('input1', 'value'),
    prevent_initial_call=True
)
def update_form_action(n_clicks, input_value):
    # 直接拼接返回最终的action路由,不需要全局变量
    return f'/charts/{input_value}'

方案2:使用dcc.Location实现跳转(更灵活)

如果不需要走Form的默认POST提交逻辑,可以直接通过回调修改页面地址实现跳转,代码更简洁:

app.layout = html.Div([
    # 新增Location组件用于控制页面跳转
    dcc.Location(id='url', refresh=True),
    dcc.Graph(
        id='example-graph',
        figure = fig,
    ),
    html.Div([
        dcc.Input(id='input1', name='name'),
        html.Button('Submit', id='submit', n_clicks=0),
    ])
])

@app.callback(
    Output("url", "href"),
    Input('submit', 'n_clicks'),
    State('input1', 'value'),
    prevent_initial_call=True
)
def redirect_to_chart(n_clicks, input_value):
    if input_value:
        return f'/charts/{input_value}'

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 10:18:02