我试图用dash和dash-bootstrap-components构建一个小表单,但我不知道如何使用表单的动作属性。
或者说,我试图将用户输入到Postgres表单中的数据保存到Postgres中,而action属性似乎就是这样做的,但我无法找到如何使用它的任何示例。
有人有使用DBC构建表单的经验吗?
编辑我的当前解决方案是(以简化的形式):
def handle_submit(n_submit, e, pass):
username = e.split('@')
pg = pd.DataFrame(e, username, pass)
if n_submit:
pg.to_sql("table", con=db.engine, if_exists="append", index=False)
return 'success'但这似乎行不通。
发布于 2021-07-11 20:58:33
默认情况下,不使用action端点
prevent_default_on_submit (布尔值;默认真):表单对提交事件调用preventDefault。如果要将表单数据发布到提交事件的操作指定的端点,请将prevent_default_on_submit设置为False。默认为True。
基于您的问题,似乎您只是想做一些提交,而没有必要的action。在这种情况下,您可以这样做:
from dash import Dash
import dash_html_components as html
import dash_bootstrap_components as dbc
from dash.dependencies import Output, Input, State
app = Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
form = dbc.Form(
id="form",
children=[
dbc.FormGroup(
[
dbc.Label("Email", className="mr-2"),
dbc.Input(id="email", type="email", placeholder="Enter email"),
],
className="mr-3",
),
dbc.FormGroup(
[
dbc.Label("Password", className="mr-2"),
dbc.Input(id="password", type="password", placeholder="Enter password"),
],
className="mr-3",
),
dbc.Button("Submit", color="primary"),
],
inline=True,
)
app.layout = html.Div([form, html.Div(id="output")])
@app.callback(
Output("output", "children"),
Input("form", "n_submit"),
State("email", "value"),
State("password", "value"),
prevent_initial_call=True
)
def handle_submit(n_submit, email, password):
# Do stuff...
return n_submit
if __name__ == "__main__":
app.run_server()在上面的回调中返回n_submit,以显示提交操作有效,但您可能希望根据需要将其更改为其他操作。
更新
根据编辑,您可以将回调更改为如下所示:
@app.callback(
Output("output", "children"),
Input("form", "n_submit"),
State("email", "value"),
State("password", "value"),
prevent_initial_call=True,
)
def handle_submit(n_submit, email, password):
username = email.split("@")
pg = pd.DataFrame(
{"email": [email], "username": [username], "password": [password]}
)
if n_submit:
pg.to_sql("table", con=db.engine, if_exists="append", index=False)
return "success"
return ""我已经改变了DataFrame的构造方式和变量名。pass是一个保留关键字,所以我不会使用它作为参数名。我还添加了一个默认返回语句。这里并不完全必要,因为prevent_initial_call设置为True,但它显示了如何解释n_submit要评估为False的情况。
https://stackoverflow.com/questions/68336401
复制相似问题