WTForms 对 HTML 表单控件 <select> 进行 SelectField 包装,从而实现下拉列表。
使用下拉列表有两种情况,
第一种直接下拉选择设定的值,然后将选择的值读取存储。这种情况比较简单,
1.首先,在form.py中定义表单以及SelectField下拉列表
app\main\form.py class SmFormAdmin(Form): status = SelectField('按类型查询',validators=[Required()] , choices=[('0', '全部'),('1', '待审核'),('2', '认证成功'),('3', '认证失败')] ) submit = SubmitField('Submit')SelectField 实例必须在其 choices 属性中设置各选项。选项必须是一个由元组组成的列表, 各元组都包含两个元素:选项的标识符和显示在控件中的文本字符串。
2.在路由中读取表单的值,直接使用或者存入数据库
app\main\views.py @main.route('/sm_admin', methods=['GET', 'POST']) @login_required def sm_admin(): user = User.query.filter_by(email=current_user.email).first() if user.user_role > 0: <strong>form = SmFormAdmin()</strong> if request.method == 'POST': if form.validate_on_submit(): <strong>sm_status = form.status.data</strong> #从表单中读取选择的值 .........................这里直接使用了读取的值,使用过程省略 return render_template('sm_admin.html', result=result, form=form, pagination=pagination) return render_template('sm_admin.html', form=form) else: return redirect(url_for('.index'))
1.数据模型定义如下:
app\models.py
class Department(db.Model): __tablename__ = 'departments' id = db.Column(db.Integer, primary_key=True) department = db.Column(db.String(100))
<pre name="code" class="python">user_department = db.Table('user_department', db.Column('user_id', db.Integer, db.ForeignKey('users.id'), primary_key=True), db.Column('department_id', db.Integer, db.ForeignKey('departments.id'), primary_key=True) )
2.定义表单,需要在初始化函数中对choices赋值
app\main\form.py class SmForm(Form): ................................其他表单类型省略 pre_department = SelectField('原学院:', coerce=int) cut_department = SelectField('现学院:', coerce=int) submit = SubmitField('Submit') <strong> def __init__(self, user, *args, **kwargs): super(SmForm, self).__init__(*args, **kwargs) self.pre_department.choices = [(pre_department.id, pre_department.department) for pre_department in Department.query.order_by(Department.department).all()] self.cut_department.choices = [(cut_department.id, cut_department.department) for cut_department in Department.query.order_by(Department.department).all()] self.user = user</strong>
choices 列表在表单的构造函数中设定,其值从 Department 模型中获取,使用一个查询按照学院id顺序排列所有学院,元组中的标识符是学院的 id,因为这是个整数,所以在 SelectField 构造函数中添加 coerce=int 参数,从而把字段的值转换为整数。
3.编写路由函数。
由于原来路由函数很复杂,就不贴上来了,只贴关键几句了:
@main.route('/sm', methods=['GET', 'POST']) @login_required @main.errorhandler(404) def sm(): user = User.query.filter_by(email=current_user.email).first() form = SmForm(user) <pre name="code" class="python"> if form.validate_on_submit(): ....................................省略其他 <pre name="code" class="python"> <strong>user.departments.append(Department.query.get(form.pre_department.data)) user.departments.append(Department.query.get(form.cut_department.data))</strong><pre name="code" class="python"> db.session.add(user) db.session.commit() flash('您已提交实名认证申请') return redirect(url_for('.sm_success')) return render_template('sm.html', form=form)