我正在研究表单的“编辑”功能。呈现表单时,字段应填充存储在数据库中的数据。此字段之一作为 SQlAlchemy AppenderBaseQuery 对象返回。这会导致在字段中预填充查询语句,而不是查询结果。
如何使用对象中的元素预填充表单?
form = MyForm(obj=MyObject)
if form.validate_on_submit():
form.populate_obj(MyObject)
该字段定义为 StringField。
注意:我通过 MyObject 来预填充表单,因为 WTForm 有一个地方form.Field.data
根本没有更新。
form = MyForm()
form.Field.data = "test" #Pre-populate Field with "test"
if validate_on_submit():
MyObject.Field = Form.Field.data #Assign data in Field to MyObject
#...
我的 Object.Field 不会用 new 更新Form.Field.data
,不知道为什么。
正如 n-Holmes 在评论中所建议的:
# Do not initiate the form with object
form = MyForm()
# Split logic to 'GET' and 'POST request'
if request.method == 'GET'
MyForm.Field.Data = ', '.join([element.attribute for element in MyForm.Field.all()]
# MyForm.Field is an AppenderBaseQuery Object >> Returns a query statement
# MyForm.Field.all() returns a list of Objects
# The list comprehension returns a list of a specific attribute for each object
# The .join combines the list to a string, separated by ", "
# This entire thing is pre-populated onto the form
# Eg: "Attribute01, Attribute02, Attribute03"
if validate_on_submit:
MyObject.Field = FunctionToUpdateField(form.Field.data)
# form.Field.data will be a string
# FunctionToUpdateField compares above string with what is stored in db ...
# determines which elements to add / remove
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句