Search code examples
pythonwtformsflask-admin

Dynamic SelectField validation fails with: "Not a valid choice"


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

Solution

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