当我尝试在Flask视图中从数据库中删除项目时,会显示以下错误
UnboundLocalError: local variable 'restaurantToDelete' referenced before assignment
@app.route('/restaurant/<int:restaurant_id>/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)
答案 0 :(得分:1)
看看其他的,当时没有定义restaurantToDelete,你的代码应该像
@app.route('/restaurant/<int:restaurant_id>/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)
答案 1 :(得分:1)
您在restaurantToDelete
- 块中定义变量if
,然后尝试在else
- 块中使用它。如果request.method
不是POST
,则该变量不存在,因为您的代码未进入if
- 块。您可以通过在检查请求类型之前获取餐馆来解决此问题:
@app.route('/restaurant/<int:restaurant_id>/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)