问题描述
这些列表看起来和我想要的一样,具有所有正确的选项,但是当我按下Submit('Add Movement')按钮时,它没有得到验证(它没有输入{{1 }}代码块)。在我添加SelectField之前,它曾经得到过验证,因此我倾向于认为我在这里做错了。
if form.validate_on_submit()
这是我的“运动”表模型:
@app.route('/movements',methods=['GET','POST'])
def movements():
form = MovementForm()
if form.validate_on_submit():
product = Product.query.filter_by(id=form.product.data).first()
from_location = Location.query.filter_by(id=form.from_location.data).first()
to_location = Location.query.filter_by(id=form.to_location.data).first()
m = Movement(product = product.name,from_location = from_location.name,to_location = to_location.name,quantity = form.quantity.data)
db.session.add(m)
db.session.commit()
movements = Movement.query.all()
products = Product.query.all()
locations = Location.query.all()
return render_template('movements.html',movements=movements,products=products,locations=locations,form=form)
form.product.choices = [(product.id,product.name) for product in Product.query.all()]
form.from_location.choices = [(location.id,location.name) for location in Location.query.all()]
form.to_location.choices = [(location.id,location.name) for location in Location.query.all()]
movements = Movement.query.all()
products = Product.query.all()
locations = Location.query.all()
return render_template('movements.html',form=form)
这是表格:
class Movement(db.Model):
id = db.Column(db.Integer,primary_key=True)
product_id = db.Column(db.Integer,db.ForeignKey('product.id'))
product = db.Column(db.String(50),nullable=False)
from_location_id = db.Column(db.Integer,db.ForeignKey('location.id'))
from_location = db.Column(db.String(50))
to_location_id = db.Column(db.Integer,db.ForeignKey('location.id'))
to_location = db.Column(db.String(50))
quantity = db.Column(db.Integer,nullable=False)
timestamp = db.Column(db.DateTime,nullable=False,default=datetime.utcNow)
解决方法
我认为我也有类似的经历,问题是表格没有针对空的选择列表进行验证。因此,在验证之前填写form.from_location.choices
(及其他)可以解决该问题:
@app.route('/movements',methods=['GET','POST'])
def movements():
form = MovementForm()
form.product.choices = [(product.id,product.name) for product in Product.query.all()]
form.from_location.choices = [(location.id,location.name) for location in Location.query.all()]
form.to_location.choices = [(location.id,location.name) for location in Location.query.all()]
if form.validate_on_submit():
# your code
# your code
return render_template('movements.html',movements=movements,products=products,locations=locations,form=form)