本文介绍了动态 SelectField 验证失败,并显示:“不是有效的选择";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的代码,我无法通过 SelectField 上的无效选择",无论是在创建表单中还是在编辑表单中...我作为选择传递的类别是 unicode,甚至所以我在 Form SelectField 中尝试了各种强制"设置
Here's my code, i can't get past the "not a valid choice" on the SelectField, being it in the creation form or the editing one... The categories i'm passing it as choices are unicode, even so i tried various "coerce" settings in the 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')
推荐答案
您可以创建自定义 SelectField 并覆盖 pre_validate 方法.像这样:
You can create your custom SelectField and overwrite pre_validate method. Like this:
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 验证失败,并显示:“不是有效的选择";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!