我在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仅包含与Product db模型匹配的属性。
表格
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包含一个我想在视图中用于创建维修的表格。base_product是一种表单,理想情况下,我想在视图中传递obj = product,因此默认值会自动填充。我也想在base_product表单上使用form.populate_obj()。
这是我在视图中创建“产品”表单的方式:
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)
但是,Product表单中的base_form不会被现有对象的默认值填充。
关于如何实现这一目标的任何建议?谢谢 :)
发现可以直接在浏览器中的Flask堆栈跟踪中运行代码之后(这有多酷?),我找到了解决问题的方法。
关键是在创建主要产品表单(在make_product_form()中)时,我
form.base_product.obj
实际上并没有真正访问obj属性。
但是,这样做form.base_product.form.process(obj=product)
就可以了!关键是使用base_product。形成以获得访问FormField内的形式。这是form.base_product的所有属性。在make_product_form()中,仅在form = form()之后评估dir():
dir(form.base_product)
[#ommitted some attributes#,
'__weakref__', '_formfield', '_obj', '_run_validation_chain',
'_translations', 'data', 'default', 'description',
'do_not_call_in_templates', 'errors', 'filters', 'flags', 'form',
'form_class', 'gettext', 'id', 'label', 'meta', 'name', 'ngettext',
'object_data', 'populate_obj', 'post_validate', 'pre_validate',
'process', 'process_data', 'process_errors', 'process_formdata',
'raw_data', 'render_kw', 'separator', 'short_name', 'type',
'validate', 'validators', 'widget' ]
这表明实际上form.base_product是一个Field,而不是Form,并且执行form.base_product.form使我获得了ProductBase表单。
希望这会有所帮助
**更新**
我只必须在GET请求上使用process(obj = product)来预先填充表单,否则在POST上,实际的表单数据将被丢弃。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句