尝试在动态WTForm字段中插入空白选项
问题描述:
我试图在现有工作动态字段(客户)中添加一个空白选项,其结果是在SOF here上找到的结果,但是出现错误。尝试在动态WTForm字段中插入空白选项
的错误是ValueError: invalid literal for int() with base 10: ''.
如果必要的话,我可以提供完整的回溯。
这里是形式 - 充满活力的领域是客户一个你可以看到:
class FilterWorkorderForm(FlaskForm):
id = IntegerField('id', validators=[Optional()])
date = DateField('Date', validators=[Optional()])
customer = SelectField('Customer', coerce=int, validators=[Optional()])
customer_po = StringField('Customer PO', validators=[Optional()])
requested_by = StringField('Requested By', validators=[Optional()])
work_description = StringField('Work Description', validators=[Optional()])
status = SelectField('Status', choices=[('Quote', 'Quote'), ('Pending', 'Pending'), ('WIP', 'WIP'), ('Complete', 'Complete'), ('TBI', 'TBI'), ('Invoiced', 'Invoiced'), ('VOID', 'VOID')])
下面是路线:
@app.route('/reports/filter_workorder', methods=['GET', 'POST'])
@login_required
def filter_workorder():
results = None
form = FilterWorkorderForm()
form.customer.choices = [(cus.id, cus.company_name) for cus in Company.query.order_by('id')]
### LINE CAUSING ERROR ### form.customer.choices.insert(0, ("", "")) ### LINE CAUSING ERROR ###
if request.method == 'POST':
if form.validate_on_submit():
try:
customer_id = form.customer.data
customer = Company.query.filter_by(id = customer_id).first_or_404()
customer_name = customer.company_name
filter_data = {'id' : form.id.data, 'date' : form.date.data, 'customer_po' : form.customer_po.data, 'customer' : customer_name,
'work_description' : form.work_description.data, 'status' : form.status.data}
filter_data = {key: value for (key, value) in filter_data.items() if value}
results = Workorder.query.filter_by(**filter_data).all()
except Exception as e:
db.session.rollback()
flash(e)
return render_template('filter_workorder.html', form = form, results = results)
return render_template('filter_workorder.html', form = form)
答
的问题呈现你的形式,特别是客户字段,用整数强制。
按照WTForms's documentation on the Select
widget:
字段必须提供一个
iter_choices()
方法,其部件将上渲染调用;此方法必须产生(value, label, selected)
的元组。
如果你看看the source code for this method:
def iter_choices(self):
for value, label in self.choices:
yield (value, label, self.coerce(value) == self.data)
有没有异常处理在这种方法失败的胁迫。在你的情况下,self.coerce(value)
被执行为int('')
,这会导致你遇到的ValueError
异常。
至少有两种解决方案:
- 删除
coerce
。 -
使用sentinel value为
0
或-1
这样来表示没有客户正在选择:form.customer.choices.insert(0, (0, ""))
该值将通过胁迫,但你需要处理这个值(取消设置“客户”字段)邮政表格处理。
这是正确的!谢谢。我应该能够自己解决这个问题。只需要调整我的路线处理来处理更改。可以了,好了。 – xGlorify