如何使用Flask WTF获取QuerySelectField当前值 [英] How to get QuerySelectField current value with Flask WTF
问题描述
如果使用 SelectField ,我们可以使用 obj
参数从数据库中获取以表单形式预先填充的当前值,例如
If using SelectField we can get the current value that prepopulate in form from database using the obj
argument, like this answer on my previous question.
现在,我想使用QuerySelectField
获取当前值.
For now, I want to get the current value using QuerySelectField
.
这是我的代码段:
def course_list():
return Course.query.all()
class PaymentForm(Form):
total_price = IntegerField(validators=[required()])
course_name = QuerySelectField('Course name', validators=[required()], query_factory=course_list)
# ....
# ....
这是路线.
@app.route('/edit_payment/<int:payment_id>', methods=['GET', 'POST'])
def edit_payment(payment_id):
payment = Pament.query.filter_by(id=payment_id).first()
course = db.session.query(Course.name).filter_by(id=payment.course_id).first()
payment_form = PaymentForm(obj=course) # here I try to use the obj argument.
# ... validate on submit
# ....
# ....
return render_template(payment=payment, payment_form=payment_form)
在我称之为PaymentForm
的路由上,我尝试解析 obj
参数,但是似乎它没有从db中预先填充当前用户的值.
On the route above which I call the PaymentForm
, I try to parse the obj
argument, but seems it did not prepopulate the value on current user from db.
这是我在Jinja2模板上的称呼:
here is how I call it on Jinja2 template:
{{ f.render_field(payment_form.course_name, value=payment.name) }}
所以,我的问题是,如何基于数据库上的当前用户值获取QuerySelectField
值.?
So, the point of my question is, how to get the QuerySelectField
value base on current user value on database..?
编辑:
这是我的模特的片段:
class Payment(db.Model):
__tablename__ = 'payment'
id = db.Column(db.Integer, primary_key=True)
course = db.relationship('Course', backref=db.backref('payment', lazy='dynamic'))
# ...
# ...
def __init__(self, course):
self.course = course
class Course(db.Model):
__tablename__ = 'course'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), unique=True)
# ...
# ...
def __init__(self, name):
self.name = name
我也试图像这样在 obj
上传递值:
And I also tried to pass the value on obj
like this:
payment = Pament.query.filter_by(id=payment_id).first()
payment_form = PaymentForm(obj=payment)
推荐答案
我通过遵循以下出色的 answer
I figure out this by following this great answer.
这篇关于如何使用Flask WTF获取QuerySelectField当前值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!