REQUEST FUNCTION FROm FLASK

Issue

I am using request.form.get("name") to get the value of an input whose type=number.

I then want to be able to compare so as to ensure that it is a postive number as follows:

number = request.form.get("name")

If number < 0:

# Do something

  1. This gives an error as follows:-

TypeError: < not supported between instances of 'str' & 'int'

Doesnt the input field already make the said request a number?

what is happening??

I tried to compare two numbers, turns out one of them is being treated as a string.

Solution

HTML input types like <input type="number"> serve only for client-side validation purposes and have no effect on what’s sent in the HTTP request. The HTTP forms will always contain text, like param1=123&param2=blah. You need to parse the values explicitly:

try:
    number = int(request.form.get('name'))
except ValueError:
    # handle the error

For more complex cases you can use a form validation library, e.g. Flask-WTF.

Answered By – bereal

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published