我的 Flask 应用程序需要帮助。我有 FlaskForm 页面并使用 QuerySelectField 以便用户可以选择仓库表单数据库。我将 SQLAlchemy 与 SQlite 数据库一起使用。
这是我的数据库模型代码:
class ozonWarehouse(db.Model):
__tablename__ = "ozonWarehouses"
id = db.Column(db.Integer, primary_key=True)
type = db.Column(db.String(32))
name = db.Column(db.String(64), index=True, unique=True)
enabled = db.Column(db.Boolean)
def __repr__(self):
return '<Ozon Warehouse {}>'.format(self.name)
这是我构建表单的代码:
class ozonUnitEcForm(FlaskForm):
...
fboWarehouseFrom = QuerySelectField('Склад отправки партии товара',
query_factory=lambda: db.session.execute(
db.select(ozonWarehouse)).scalars(),
get_label='name')
...
submit = SubmitField('Рассчитать')
使用此表单加载页面时,我需要在 QuerySelectField 中选择默认值。必须选择的仓库的 ID 位于字典“productData”中,键为“fboWarehouseFrom”。因此,如果productData['fboWarehouseFrom'] = 3,则必须在QuerySelectField中选择ID = 3的仓库。
为了更清楚,这是数据库表的屏幕截图: 数据库表截图
这是我处理该页面的 URL 的代码:
@app.route('/ozon-unit-economy', methods=['GET', 'POST'])
def ozonUnitEconomy():
ozonProductId = request.args.get('id')
productData = dict()
form = ozonUnitEcForm()
if form.validate_on_submit():
productData = func.loadOzonProdUEData(form, None, ozonProductId)
calcResults, miscData, currentDate = func.calcOzonUnitEconomy(productData, form.date.data)
else:
productData = func.loadOzonProdUEData(None, None, ozonProductId)
calcResults, miscData, currentDate = func.calcOzonUnitEconomy(productData, date.today())
...
form.fboWarehouseFrom.default = productData['fboWarehouseFrom']
...
return render_template('ozon-unit-economy.html', title='Юнит-экономика товара Ozon', form=form, productData = productData, miscData = miscData, calcResults = calcResults)
在此代码中,仓库ID的正确值被分配给productData['fboWarehouseFrom'],然后我用它来设置form.fboWarehouseFrom.default的值。我认为设置 form.fboWarehouseFrom.default 的值会在 QuerySelectField 中选择具有此 ID 的仓库,但它不起作用,QuerySelectField 没有选择。
请指出哪里出了问题以及如何纠正。谢谢!
创建表单后更新 ozonUnitEconomy 路由中的 fboWarehouseFrom.data 属性:
@app.route('/ozon-unit-economy', methods=['GET', 'POST'])
def ozonUnitEconomy():
ozonProductId = request.args.get('id')
productData = dict()
form = ozonUnitEcForm()
if form.validate_on_submit():
productData = func.loadOzonProdUEData(form, None, ozonProductId)
calcResults, miscData, currentDate = func.calcOzonUnitEconomy(productData, form.date.data)
else:
productData = func.loadOzonProdUEData(None, None, ozonProductId)
calcResults, miscData, currentDate = func.calcOzonUnitEconomy(productData, date.today())
# Set the selected warehouse ID for the QuerySelectField
selected_warehouse_id = productData.get('fboWarehouseFrom')
if selected_warehouse_id:
form.fboWarehouseFrom.data = db.session.execute(
db.select(ozonWarehouse).filter_by(id=selected_warehouse_id)
).scalars().first()
return render_template(
'ozon-unit-economy.html',
title='Юнит-экономика товара Ozon',
form=form,
productData=productData,
miscData=miscData,
calcResults=calcResults
)