我正在创建一个Web应用程序,用户操作会影响某些条形图(见下面的gif)。有时,更改不会被保存。当我重新加载页面时,会显示更改的条形图(表示已保存用户的操作)。当我再次重新加载页面时,有时会显示更新的条形图和相应的列表。其他时候,他们不是。
以下是该视图的代码:
@app.route('/')
def home():
'''homepage for application'''
# redirect users who go to home page but aren't logged in
if not current_user.is_authenticated:
return redirect(url_for("landing"))
# reset the session
db.session.flush()
# get most recent entered weight
try:
last_weight = WeightEntry.query.filter_by(user_id = current_user.user_id).order_by(WeightEntry.date)[-1]
except IndexError:
return error("No weight recorded. Please contact support.")
return render_template("home.html",
today= Today(current_user.user_id),
foods = [food for food in FoodEntry.query.filter_by(user_id=current_user.user_id).all() if food.is_today() == True],
options = sorted(Food.query.filter(Food.user_id==current_user.user_id).all(), key=lambda x: x.name),
last_weight = last_weight)
我添加了db.session.flush()
以尝试解决问题,但这并没有奏效。
更改(已记录的食物)存储在此处:
@app.route("/log_food", methods=["POST", "GET"])
@login_required
def log_food():
# add foods given by the user
if request.method == "POST":
for food in request.form.getlist("logged_food"):
try:
added_food = Food.query.filter_by(user_id=current_user.user_id, name=food).first()
x = FoodEntry(
food_id = added_food.food_id,
user_id = current_user.user_id)
db.session.add(x)
db.session.commit()
except:
return error("Unable to log food.")
return redirect(url_for("home"))
我很感激我能得到的任何帮助。
谢谢!
答案 0 :(得分:0)
我通过将db.session.commit()
添加到页面函数来修复它。
例如,对于主页:我做了:
@app.route('/')
def home():
'''homepage for application'''
db.session.commit()
...