我正在制作一个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"))如果能得到任何帮助,我将不胜感激。
谢谢!
发布于 2017-08-05 05:42:46
我通过将db.session.commit()添加到页面函数来修复它。
例如,对于主页:我做到了:
@app.route('/')
def home():
'''homepage for application'''
db.session.commit()
...https://stackoverflow.com/questions/45007620
复制相似问题