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)
修改说明
日期下拉框回调:
- 新增
Output("field-dropdown", "value")输出项,获取日期列表后自动将第一个日期设为选中值 - 页面加载时,由于初始
value为None,会自动触发回调完成初始化
- 新增
文章下拉框回调:
- 新增
Output("results-dropdown", "value")输出项,获取对应日期的文章列表后,自动选中第一篇文章的_id - 将
artcoll.find()返回的游标转为列表,避免空列表时触发索引错误
- 新增
空值兼容:
- 增加了日期列表、文章列表为空的判断,保证页面在无数据时也能正常运行
内容的提问来源于stack exchange,提问作者Robert Alexander
相关产品推荐
相关产品推荐

