How to get QuerySelectField current value with Flask WTF

て烟熏妆下的殇ゞ 提交于 2019-12-24 08:07:01

问题


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.

For now, I want to get the current value using QuerySelectField.

Here is the snippet of my code:

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)
    # ....
    # ....

And here is the route.

@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)

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.

here is how I call it on Jinja2 template:

{{ f.render_field(payment_form.course_name, value=payment.name) }}

So, the point of my question is, how to get the QuerySelectField value base on current user value on database..?

EDIT:

Here is the snippet of my model:

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

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)

回答1:


I figure out this by following this great answer.



来源:https://stackoverflow.com/questions/57863668/how-to-get-queryselectfield-current-value-with-flask-wtf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!