UnboundLocalError: local variable 'restaurantToDelete' referenced before assignment Flask app
<p>When I try to delete an item from the database in a Flask view, the following error is shown</p>

<pre><code>UnboundLocalError: local variable 'restaurantToDelete' referenced before assignment
</code></pre>



<pre><code>@app.route('/restaurant/&lt;int:restaurant_id&gt;/delete',methods=['GET','POST'])
def deleteRestaurant(restaurant_id):
    if request.method=='POST':
        restaurantToDelete=session.query(Restaurant).filter_by(id=restaurant_id).one()
        session.delete(restaurantToDelete)
        session.commit()
        return redirect(url_for('showRestaurants'))
    else:
        return render_template('deleterestaurant.html',restaurant=restaurantToDelete)
</code></pre>

<p>You're defining the variable <code>restaurantToDelete</code> inside an <code>if</code>-block, and then you try to use it inside the <code>else</code>-block. If the <code>request.method</code> is not <code>POST</code>, the variable does not exist, because your code does not enter the <code>if</code>-block. You can fix this by fetching the restaurant before checking for the request type:</p>

<pre><code>@app.route('/restaurant/&lt;int:restaurant_id&gt;/delete',methods=['GET','POST'])
def deleteRestaurant(restaurant_id):
    restaurantToDelete=session.query(Restaurant).filter_by(id=restaurant_id).one()
    if request.method=='POST':
        session.delete(restaurantToDelete)
        session.commit()
        return redirect(url_for('showRestaurants'))
    else:
        return render_template('deleterestaurant.html',restaurant=restaurantToDelete)
</code></pre>

python flask sqlalchemy