Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask-WTF dynamic select field gives "None" as a string

I have an empty select field that has choices that I define during run time:

myfield = SelectField('myfield', validators=[Optional()])

I'm trying to have this work with a GET request which looks like this:

@app.route('/', methods=['GET'])
def myresponse():
    form = myform(csrf_enabled=False)
    form.myfield.choices = (('', ''), ('apples', 'apples'), ('pears', 'pears'))

Then when I try to validate on an empty form. (I go to myapp.com with no GET parameters)

    if not form.validate():
        return search_with_no_parameters()
    else:
        return search_with_parameters(form) #this gets run

When my search_with_parameters function tries to use the form variables, it checks to make sure that the form.myfield.data is not Falsey (not an empty string). If it is not Falsey, a search with that parameter is done. If it is Falsey, that parameter is ignored. However, on an empty form submission, form.myfield.data is "None" as a string. And a search with "None" is done. I could validate against the "None" string but I think this defeats the purpose of using this module in the first place. Is there any way to make this just return an empty string or the real None value?

like image 203
user1005909 Avatar asked Feb 17 '16 15:02

user1005909


1 Answers

I have found that adding a default parameter of the empty string solves the problem.

It appears that this is necessary to support the empty string as a choice/option with a SelectField.

Example:

myfield = wtf.fields.SelectField(
    u"My Field",
    validators=[wtf.validators.Optional()],
    choices=[(('', ''), ('apples', 'apples'), ('pears', 'pears'))],
    default=''
)
like image 112
wodow Avatar answered Oct 04 '22 02:10

wodow