这是我的代码,我无法通过"不是有效的选择"在SelectField上,无论是创建形式还是编辑形式...我将其作为选择传递的类别是unicode,即便如此,我尝试了各种各样的" coerce" Form SelectField中的设置
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')
答案 0 :(得分:1)
您可以创建自定义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'))