Dynamic SelectField validation fails with: “Not a valid choice”

人走茶凉 提交于 2019-12-08 04:11:20

问题


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')

回答1:


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'))


来源:https://stackoverflow.com/questions/28718138/dynamic-selectfield-validation-fails-with-not-a-valid-choice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!