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

I have an empty selection field that has a choice that I define at runtime:

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

I am trying to do this work with a GET request that 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 check on a blank form. (I go to myapp.com without 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 form variables, it checks that it is form.myfield.datanot Falsey (and not an empty string). If it is not Falsey, a search is performed with this parameter. If it is Falsey, this parameter is ignored. However, when submitting an empty form form.myfield.datathere is "None"as a string. And the search is done with "None". I could approve the line "None", but I think this defeats the purpose of using this module in the first place. Is there any way to do this simply return an empty string or a real value None?

+4
source share
2 answers

I found that adding defaultan empty string parameter solves the problem.

, / SelectField.

:

myfield = wtf.fields.SelectField(
    u"My Field",
    validators=[wtf.validators.Optional()],
    choices=[(('', ''), ('apples', 'apples'), ('pears', 'pears'))],
    default=''
)
+5

, . coerce '' 0 :

myfield = SelectField('myfield', validators=[Optional()], coerce=int)
...
form.myfield.choices = ((0, ''), (1, 'apples'), (2, 'pears'))

, , . , , .

+2

Source: https://habr.com/ru/post/1629201/


All Articles