如何使用Flask WTF获取SelectField当前值 [英] How to get SelectField current value with Flask WTF

查看:1050
本文介绍了如何使用Flask WTF获取SelectField当前值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Flask-WTF 创建性别表单,这是我的代码段:

I making a gender form using Flask-WTF, here is the snippet of my code:

class Gender(enum.Enum):
    Male = 'Male'
    Female = 'Female'

    def __str__(self):
        return self.value

gender = [(str(y), y) for y in (Gender)]

class EditStudentForm(Form):
    gender = SelectField('Gender', choices=gender)

@app.route('/edit_student')
def edit_student():
    student = Student.query.filter_by(id=student_id).first()
    student_form = EditStudentForm()
    # ... validate on submit
        # ....
        # ....
    return render_template(student=student, student_form=student_form)

该代码已经可以工作了,包括我可以将数据插入数据库中了.

That code already works, included I can insert the data to the database.

但是,如果数据库上当前的用户性别值是女性,则每当我刷新浏览器时,表单都不会获得当前值.

But, if the current user gender value on database is Female, whenever I refresh the browsers, the form did not get the current value.

在HTML中,我希望它像这样:

In HTML I want it to be like this:

// edit form
<form>
  <input type="" value="currentUserValueFromDatabase">
</form>

我尝试通过这种方式获取当前值:

I try to get current value using this way:

{{ f.render_field(student_form.gender, value=student.gender) }}

但是它并没有从当前用户性别中预先填充当前值.

But it didn't prepopulate the current value from current user gender.

所以我想要的是在selectfield上显示当前值,或者根据数据库上的当前用户值预填充selectfield.

So what I want is to to display current value on selectfield or prepopulate the selectfield according to the current user value on the database.

推荐答案

student作为obj关键字参数传递给EditStudentForm,例如:

Pass student to the EditStudentForm as the obj keyword argument, e.g.:

student_form = EditStudentForm(obj=student_form)

为什么?来自 WTForms文档:

obj –如果formdata为空或未提供,则检查该对象是否存在 与表单字段名称匹配的属性,这些字段名称将用于字段 值.

obj – If formdata is empty or not provided, this object is checked for attributes matching form field names, which will be used for field values.

在处理GET请求时构造表单时,没有表单数据,因此它将使用对象数据.

When you construct the form when handling a GET request, there is no form data, so it will use the object data.

这篇关于如何使用Flask WTF获取SelectField当前值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆