tzazo
tzazo

Reputation: 363

Can't set default value for form data in Flask

I have a Flask route, defined like this:

@app.route('/test/', methods=['POST'])
def test():
    number = request.form.get('my_number', 555) # number == ''
    return str(number)

If I make a POST request to /test/ with my_number empty/missing, I expect the local variable number to be set to 555 (the default). Instead, number is an empty string ''.

The only way I'm able to get the default value to be respected (number == 555) is to use or like this:

@app.route('/test/', methods=['POST'])
def test():
    number = request.form.get('my_number') or 555 # number == 555
    return str(number)

Any idea what's going wrong?

Upvotes: 4

Views: 6079

Answers (1)

sd191028
sd191028

Reputation: 78

The issue is that for your input, request.form.get('number') is always retrieving an empty string. Because there is something to retrieve, it never uses the default value even if you pass it as the second parameter.

or, however, treats '' as false, so it will pick 555. (see "Using or With Common Objects" https://realpython.com/python-or-operator/)

This implies that whenever you are accessing this url, the form you are posting has an entry for "number".

Upvotes: 5

Related Questions