gpt4 book ai didi

python - WTForm FormField 填充值

转载 作者:太空宇宙 更新时间:2023-11-03 16:52:14 25 4
gpt4 key购买 nike

我在 WTForms 中设置 FieldForm 的默认值时遇到问题。

models.py

class RepairCategory(db.Model):
name = ...
class Repair(db.Model):
price = ..
category_id [FK] = ...
product_id [FK]
class Product(db.Model):
name = ...
description = ...
color = ...

ProductBase 仅包含与产品数据库模型匹配的属性。
forms.py

class NewRepair(Form):
#this is okay - it get's populated
repair_category = QuerySelectField("Repair category",
query_factory=get_categories)
price = DecimalField()

class ProductBase(Form):
name = StringField("Name ", validators=[DataRequired(), Length(1, 64)])
color = StringField("Color ", validators=[DataRequired(), Length(1, 64)])
description = TextAreaField("Description")
active = BooleanField()

class Product(Form):
base_product = FormField(ProductBase)
add_repairs = FormField(NewRepair)
submit = SubmitField('Submit')

add_repairs 包含一个表单,我想在 View 中使用它来创建修复。理想情况下,我想在 View 中传递 obj=product ,以便自动填充默认值。我也想在 base_product 表单上使用 form.populate_obj() 。

以下是我在 View 中创建产品表单的方法:

def make_product_form(form=None, product=None, **kwargs):
form = form()
form.base_product.obj = product
return form

然后,在处理 POST 时,我想做:

def product(id):
product = Product.query.get_or_404(id)

form = make_product_form(form=Product,product=product)

if form.validate_on_submit():
product_form = form.base_product
product_form.populate_obj(product)

但是,产品表单中的 base_form 不会填充现有对象的默认值。

关于如何实现这一目标有什么建议吗?谢谢:)

最佳答案

使用表单process方法用对象的属性值填充表单字段。
使用表单 populate_obj 方法用表单字段中的值填充对象的属性。
注意:对象属性的名称必须与表单字段的名称匹配。

流程示例:

>>> class MyObj(object):
... name = "object's name"
>>> from wtforms import Form, StringField
>>> class MyForm(Form):
... name = StringField("Form's name")
>>> my_obj = MyObj()
>>> my_obj.name
"object's name"
>>> my_form = MyForm()
>>> print my_form.name.data
None
>>> my_form.process(obj=my_obj)
>>> my_form.name.data
"object's name"

populate_obj 示例:

>>> my_form.name.data = "Form's name"
>>> my_form.name.data
"Form's name"
>>> my_obj.name
"object's name"
>>> my_form.populate_obj(my_obj)
>>> my_obj.name
"Form's name"

关于python - WTForm FormField 填充值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35749962/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com