我解决这个问题的方法是使用SQLFORM.factory 而不是SQLFORM。
1。我提取了表中定义的字段
fields = [field for field in db.customer]
2。附加了我想要的新字段
fields += [
Field('customer_type','string', label=T('Customer Type'),
requires=IS_IN_SET(customer_types, zero=None, sort=False)),
Field('another_field','string', label=T('Another Field')),
]
3。使用 SQLFORM.factory 生成表单
form = SQLFORM.factory(
*fields,
formstyle='bootstrap',
_class='customer form-horizontal',
table_name='customer'
)
*注意fields之前的星号是必要的
4。仍然使用form.process().accepted,但随后计算出我需要的内容,然后手动处理数据库插入
if form.process().accepted:
...
form.vars.some_nonwritable_field = calculate_complicated_value()
db.customer.insert(**db.customer._filter_fields(form.vars))
...
_filter_fields 防止动态添加的字段成为插入的一部分。
这样我可以在表单中添加经过验证但不属于插入内容的附加字段。