我有一個 Flask 表單,它可以完美運行并將值存盤在我的資料庫中,但它似乎既成功(將值發布到資料庫并顯示成功閃存)又失敗(顯示錯誤且不重定向)。
查看.py
from flask import render_template, Blueprint, request, redirect, url_for, flash
from project import db
from .models import Items
from .forms import ItemsForm
items_blueprint = Blueprint('items', __name__, template_folder='templates')
@items_blueprint.route('/', methods=['GET', 'POST'])
def all_items():
all_user_items = Items.query.filter_by()
return render_template('all_items.html', items=all_user_items)
@items_blueprint.route('/add', methods=['GET', 'POST'])
def add_item():
form = ItemsForm(request.form)
if request.method == 'POST':
if form.validate_on_submit():
try:
new_item = Items(form.name.data, form.notes.data)
db.session.add(new_item)
db.session.commit()
flash('Item added', 'success')
return redirect(url_for('all_items'))
except:
db.session.rollback()
flash('Something went wrong', 'error')
return render_template('add_item.html', form=form)
輸出示例

可能是什么導致了這種情況,因為我認為這可能是其中之一。
uj5u.com熱心網友回復:
由于@NoCommandLine 的回答,我對此進行了調查。關鍵是,該all_items函式位于藍圖中,而不是應用程式的基礎中。要重定向到您要寫入的內容redirect(url_for(".all_items")(注意字串第一個位置的句號)。請參閱 的檔案url_for,有一個包含index函式的藍圖示例。句號使其在當前路線所在的同一藍圖中進行搜索。
uj5u.com熱心網友回復:
這完全取決于錯誤發生的位置。既然它閃了('Item added', 'success'),就說明你的錯誤就行了redirect(url_for('all_items'))。
您應該查看代碼redirect(url_for('all_items'))并檢查all_user_items = Items.query.filter_by(). 也許那個查詢是錯誤的。您也可以嘗試列印出except塊中的錯誤以查看它是什么
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/372066.html
