diegoap09
diegoap09

Reputation: 23

How can I loop through form’s in flask/python?

I have one page HTML with few submit buttons with different names and values. I have all the names of the buttons in one db in SQL. When the user enter in the page usually he click just in one button each time and the form is submitted. How can I loop through this buttons in my flask/python program?

connection = sqlite3.connect('world.db')
cursor = connection.cursor()


sqlite_select_query = """SELECT name FROM countries"""
cursor.execute(sqlite_select_query)
records = cursor.fetchall()
for row in records:
    wish = request.form[row[0]]
    try:
            db.execute("INSERT INTO userinput (user_id, wish, country_name) VALUES (?, ?, ?)", user_id, wish, row[0])
                    
    except ValueError:
            db.execute("UPDATE userinput SET wish = ? WHERE user_id =? AND country_name=?", wish, user_id, row[0] )
            
    except:
        pass

I have one error 400 Bad request.

Ps.: I already tried to put the value of row between ' and ". Doesn't changed anything.

If I put my request.form inside the try session, it just pass. I put before few "prints" to see where is the error and see that is in the request form.

If I put the name direct in request form and outside the loop for example ‘’’ request.form[“Brazil”]’’’ I can insert in the database with no problems. Thanks.

Upvotes: 2

Views: 822

Answers (1)

kosciej16
kosciej16

Reputation: 7138

I am pretty sure request.form does not contain all countries, just the one associatted button is clicked. You could look at server logs, probably you see info about missing key in request.form. So what you want to is find that specific one:

wish = request.form.get(row[0])
if wish is None:
    continue

Upvotes: 2

Related Questions