尝试在动态WTForm字段中插入空白选项

2024-04-28 21:47:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在SOF here上找到一个结果后,在现有的工作动态字段(customer)中添加一个空白选项,但是得到了一个错误。在

错误是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')])

路线如下:

^{pr2}$

Tags: id错误动态customeroptionalwipquoteint
1条回答
网友
1楼 · 发布于 2024-04-28 21:47:43

问题是用整数强制呈现表单,特别是customer字段。在

根据WTForms's documentation on the ^{} widget

The field must provide an iter_choices() method which the widget will call on rendering; this method must yield tuples of (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异常。在

至少有两种解决方案:

  1. 删除coerce。在
  2. 使用sentinel value例如0或{}表示没有选择客户:

    ^{pr2}$

    此值将传递强制,但您将需要处理此值(以取消设置“customer”字段)的后期处理。

相关问题 更多 >