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

Plotly Dash联动下拉框默认值配置问题:自动加载初始选项

解决联动下拉框初始自动选中问题

关键修改点

  • 让日期下拉框在页面加载时自动选中首个日期
  • 触发文章下拉框自动加载对应日期的文章,并自动选中首篇文章

修改后的完整代码

# Build Components
app = Dash(__name__, external_stylesheets=[dbc.themes.SOLAR])
mydates = dcc.Dropdown(
    id="field-dropdown", options=[], value=None
)  # will be populated by article dates
myarticles = dcc.Dropdown(
    id="results-dropdown", options=[], value=None
)  # will be populated by articles for a given date

# Define the layout of the app
app.layout = dbc.Container(
    [
        dbc.Row(
            [dbc.Col([dbc.NavbarBrand("My Dashboard")], width=3)],
            justify="center",
        ),
        dbc.Row([dbc.Col([mydates], width=3)]),
        dbc.Row([dbc.Col([myarticles], width=3)]),
    ],
    fluid=True,
)

# 修改第一个回调:同时更新下拉框选项和默认选中值
@app.callback(
    [Output("field-dropdown", "options"), Output("field-dropdown", "value")],
    Input("field-dropdown", "value")  # 初始value为None时触发回调
)
def populate_field_dropdown(selected_value):
    """Get distinct values from the MongoDB collection articledatepub field"""
    art_dates = artcoll.distinct("articledatepub")
    options = [{"label": f, "value": f} for f in art_dates]
    # 若存在日期,自动选中第一个
    default_value = art_dates[0] if art_dates else None
    return options, default_value

# 修改第二个回调:同时更新文章选项和默认选中首篇文章
@app.callback(
    [Output("results-dropdown", "options"), Output("results-dropdown", "value")],
    Input("field-dropdown", "value")
)
def populate_results_dropdown(selected_value):
    """show issues for the selected date in dropdown"""
    print(f"first dropdown passed {selected_value} to second one")
    if selected_value is None:
        return [], None
    # Fetch the documents in the MongoDB collection,转成列表方便操作
    mongofilter = {"articledatepub": {"$eq": selected_value}}
    documents = list(artcoll.find(filter=mongofilter))
    options = [
        {"label": str(d["articleid"]), "value": str(d["_id"])} for d in documents
    ]
    # 若存在文章,自动选中第一篇
    default_article = options[0]["value"] if options else None
    return options, default_article

# Define the main function to run the app
if __name__ == "__main__":
    app.run_server(debug=True)

修改说明

  1. 日期下拉框回调:

    • 新增Output("field-dropdown", "value")输出项,获取日期列表后自动将第一个日期设为选中值
    • 页面加载时,由于初始value为None,会自动触发回调完成初始化
  2. 文章下拉框回调:

    • 新增Output("results-dropdown", "value")输出项,获取对应日期的文章列表后,自动选中第一篇文章的_id
    • 将artcoll.find()返回的游标转为列表,避免空列表时触发索引错误
  3. 空值兼容:

    • 增加了日期列表、文章列表为空的判断,保证页面在无数据时也能正常运行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 10:12:41