Flask 表单提交成功和错误
Flask form submit both succeeds and errors
我有一个烧瓶形式,它可以完美地工作并将值存储在我的数据库中,但它似乎既成功(将值发布到数据库并显示成功闪存)又失败(显示错误并且不重定向)。
view.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)
输出示例
可能是什么原因造成的,我认为是其中之一。
这完全取决于错误发生的位置。由于它闪烁 - ('Item added', 'success')
,这意味着您的错误在 redirect(url_for('all_items'))
.
行
您应该查看 redirect(url_for('all_items'))
的代码并检查 all_user_items = Items.query.filter_by()
是否存在问题。也许那个查询是错误的。你也可以尝试把except
块中的错误打印出来看看是什么
因为@NoCommandLine 的回答,我调查了它。关键是,all_items
函数位于蓝图中,而不是应用程序的基础中。要重定向到它,您需要编写 redirect(url_for(".all_items")
(注意字符串第一个位置的句号)。请参阅 the documentation for url_for
,其中有一个包含 index
函数的蓝图示例。句号使其在当前路线所在的同一蓝图中搜索。
我有一个烧瓶形式,它可以完美地工作并将值存储在我的数据库中,但它似乎既成功(将值发布到数据库并显示成功闪存)又失败(显示错误并且不重定向)。
view.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)
输出示例
可能是什么原因造成的,我认为是其中之一。
这完全取决于错误发生的位置。由于它闪烁 - ('Item added', 'success')
,这意味着您的错误在 redirect(url_for('all_items'))
.
您应该查看 redirect(url_for('all_items'))
的代码并检查 all_user_items = Items.query.filter_by()
是否存在问题。也许那个查询是错误的。你也可以尝试把except
块中的错误打印出来看看是什么
因为@NoCommandLine 的回答,我调查了它。关键是,all_items
函数位于蓝图中,而不是应用程序的基础中。要重定向到它,您需要编写 redirect(url_for(".all_items")
(注意字符串第一个位置的句号)。请参阅 the documentation for url_for
,其中有一个包含 index
函数的蓝图示例。句号使其在当前路线所在的同一蓝图中搜索。