Flask-WTForms - QuerySelectField设置表单选择选项值

时间:2018-02-28 08:47:42

标签: python-2.7 flask-sqlalchemy flask-wtforms

我有两个models - cell.CellType == CellType.Blank,其中有Employee的外键引用。

views.py

Role

forms.py

@admin.route('/employees/assign/<int:id>', methods=['GET', 'POST'])
@login_required
def assign_employee(id):
'''
Assign a role to an employee
'''
check_admin()

employee = Employee.query.get_or_404(id)

# prevent admin from being assigned a role
if employee.is_admin:
    abort(403)

form = EmployeeAssignForm(obj=employee)
if form.validate_on_submit():
    employee.role = form.role.data
    db.session.add(employee)
    db.session.commit()
    flash('You have successfully assigned a role!')

    # redirect to the employees page
    return redirect(url_for('admin.list_employees'))

return render_template('admin/employees/employee.html',
                       employee=employee, form=form,
                       title='Assign Employee')

现在,使用class EmployeeAssignForm(FlaskForm): ''' Form for admin to assign roles to employees ''' role = QuerySelectField(query_factory=lambda: Role.query.all(), get_label='name', allow_blank=True, blank_text=(u'Select a role'), get_pk=lambda x: 'id') submit = SubmitField('Submit') ,我在html表单网页视图中获得get_pk=lambda x: 'id',无论我选择哪个<option value="id">选项,第一个选项始终会被选中。

如何在表单中将Role的{​​{1}}设置为选项值并选择它?

干杯!

1 个答案:

答案 0 :(得分:0)

请尝试get_pk=lambda x: x.id