Form表单是Web应用中最基础的一部分,网上大部分说明了新建表单的使用方法,由于使用模板语言,数据没有双向绑定,再需要重新编辑就比较困难。
我们可以在视图函数里动态生成表单:
from app.form import EdituserForm
user_id = request.args.get("user_id")
user = db.session.query(User).get(user_id) #查询已存储数据
depts = [tuple(i) for i in Department.query.with_entities(Department.id, Department.name).all()]
roles = [tuple(i) for i in Department.query.with_entities(Role.id, Role.name).all()]
users = [tuple(i) for i in User.query.with_entities(User.id, User.username).all()]
#动态表单修改原数据
class EditForm(EdituserForm):
pass
setattr(EditForm,'dept_id',SelectField("部门", choices=depts,validators=[DataRequired()],default=user.dept_id))
setattr(EditForm,'leader_id',SelectField("直属上级", choices=users,validators=[DataRequired()],default=user.leader_id))
setattr(EditForm,'role_id',SelectField("角色", choices=roles,validators=[DataRequired()],default=2))
setattr(EditForm,'submit',SubmitField('提交'))
form = EditForm()
if form.validate_on_submit():
#数据库修改逻辑
.....
return render_template('form.html', form=form)
表单类中定义不需要修改的字段
class EdituserForm(FlaskForm):
# 修改表单,视图动态生成
username = StringField('姓名', validators=[DataRequired(), Length(1, 64)],render_kw={"readonly": "readonly"})
这样前端页面就会回填数据