Home > Net >  Python not executing past 1st if statement
Python not executing past 1st if statement

Time:04-08

I'm trying to make a simple POST to database based on the button clicked in the html. My issue is that python doesn't seem to iterate past the 1st if: I changed the order of the ifs and the first always works and the rest gives a 400 bad request error at line 34 (request.form['submit_button_pizza'])

@app.route('/<tableId>/menu',  methods=['GET', 'POST'])
def menu(tableId=None):
    conn = get_db_connection()
    pizzas = conn.execute('SELECT * FROM pizzas').fetchall()
    drinks = conn.execute('SELECT * FROM drinks').fetchall()
    desserts = conn.execute('SELECT * FROM desserts').fetchall()
    clientOrder = conn.execute('SELECT * FROM clientOrder').fetchall()
    
    conn.commit()
    
    
    if request.method == 'POST':
        if request.form['submit_button_pizza']:
            pass 
            conn.execute('INSERT INTO clientOrder (tableId, pizza) VALUES (?, ?)',[tableId, request.form['submit_button_pizza']])
            conn.commit()
            return render_template('menu.html', pizzas=pizzas,drinks=drinks, desserts=desserts, tableId=tableId)

        if request.form['submit_button_drink']:
            pass 
            conn.execute('INSERT INTO clientOrder (tableId, drink) VALUES (?, ?)',[tableId, request.form['submit_button_drink']])
            conn.commit()
            return render_template('menu.html', pizzas=pizzas,drinks=drinks, desserts=desserts, tableId=tableId)
            
        if request.form['submit_button_dessert']:
            pass 
            conn.execute('INSERT INTO clientOrder (tableId, dessert) VALUES (?, ?)',[tableId, request.form['submit_button_dessert']])
            conn.commit()
            return render_template('menu.html', pizzas=pizzas,drinks=drinks, desserts=desserts, tableId=tableId)
        else:
            return render_template('menu.html', pizzas=pizzas,drinks=drinks, desserts=desserts, tableId=tableId)

    elif request.method == 'GET':
        return render_template('menu.html', pizzas=pizzas,drinks=drinks, desserts=desserts, tableId=tableId)

How do I tell python to go to the next if if the first statement doesn't exist (because I didn't click that button) ?

Thanks for any help

CodePudding user response:

The issue is the request.form['submit_button_pizza'] condition check. If your form does not have the key "submit_button_pizza", this will cause an error.

Try instead with a request.form.get('submit_button_pizza') to check if the key exists and then proceed.

Another thing : if your form is going to have only one submit condition at a time, then use a if-elif-elif-else sequence to just check one of the conditions. If your current if-if-if-else is by design then ignore this comment :)

  • Related