动态 SelectField 验证失败:"Not a valid choice"
Dynamic SelectField validation fails with: "Not a valid choice"
这是我的代码,我无法通过 SelectField 上的 "not a valid choice",无论是在创建表单还是编辑表单中...我作为选择传递给它的类别是 unicode,即便如此,我还是在表单 SelectField
中尝试了各种 "coerce" 设置
class ProductsView(MyModelView):
create_template = '/admin/edit-products.html'
form = ProductForm
def create_form(self, model=None):
form = self.form()
choices = list(db.db.categories.find())
choices.sort(key=lambda x: x['order'])
sorted_choices = [(str(cat['name']), cat['name']) for cat in choices]
print sorted_choices
form.category.choices = sorted_choices
if model:
form.name.data = model['name']
form.order.data = int(model['order'])
return form
def edit_form(self, obj):
try:
pk = self.get_pk_value(obj)
if not pk:
raise ValueError('Document does not have _id')
model = db.db.products.find_one(pk)
form = self.create_form(model)
return form
except Exception as ex:
print ex
flash(gettext('Failed to edit product. %(error)s', error=str(ex)),
'error')
您可以创建自定义 SelectField 并覆盖 pre_validate 方法。像这样:
class MySelectField(SelectField):
def pre_validate(self, form):
for v, _ in self.choices:
if your validation:
break
else:
raise ValueError(self.gettext('Not a valid choice'))
这是我的代码,我无法通过 SelectField 上的 "not a valid choice",无论是在创建表单还是编辑表单中...我作为选择传递给它的类别是 unicode,即便如此,我还是在表单 SelectField
中尝试了各种 "coerce" 设置class ProductsView(MyModelView):
create_template = '/admin/edit-products.html'
form = ProductForm
def create_form(self, model=None):
form = self.form()
choices = list(db.db.categories.find())
choices.sort(key=lambda x: x['order'])
sorted_choices = [(str(cat['name']), cat['name']) for cat in choices]
print sorted_choices
form.category.choices = sorted_choices
if model:
form.name.data = model['name']
form.order.data = int(model['order'])
return form
def edit_form(self, obj):
try:
pk = self.get_pk_value(obj)
if not pk:
raise ValueError('Document does not have _id')
model = db.db.products.find_one(pk)
form = self.create_form(model)
return form
except Exception as ex:
print ex
flash(gettext('Failed to edit product. %(error)s', error=str(ex)),
'error')
您可以创建自定义 SelectField 并覆盖 pre_validate 方法。像这样:
class MySelectField(SelectField):
def pre_validate(self, form):
for v, _ in self.choices:
if your validation:
break
else:
raise ValueError(self.gettext('Not a valid choice'))