wtform表单中动态添加的字段无法显示
1、form构造函数中动态添加字段,打开浏览器第一次仅能显示form属性申明中的字段:projectIdentifier和submit,无法显示构造函数中动态添加的字段,必须刷新一遍才能显示动态添加的字段,有木有办法不刷新,由于动态字段中的内容较多,不想在类属性申明阶段一个个写死。
主要代码如下:
app.order.forms.py
class EmployeeForm(Form):
projectIdentifier = StringField('项目编号', validators=[
DataRequired('请输入项目编号'),
Length(min=4, max=25, message='length must between 4 and 25')
])
submit = ButtonField('确定')
def __init__(self, *args, **kwargs):
super(EmployeeForm, self).__init__(*args, **kwargs)
for job in Job.query.all():
setattr(self.__class__, job.name, SelectField(job.label, coerce=int))
for job in Job.query.all():
getattr(self, job.name).choices = [(user.id, user.username) for user in User.query.all()]
app.models.py
class Job(db.Model):
__tablename__ = 'jobs'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), unique=True)
duties = db.Column(db.Integer)
label = db.Column(db.String(64))
description = db.Column(db.String(64))
users = db.relationship('Registration', backref='job', lazy='dynamic')
app.order.view.py
@order.route('/employee')
def employee():
form = EmployeeForm()
projectNo = request.args.get('projectNo')
return render_template('order/employee.html', projectNo=projectNo,form=form)
template/order/employee.html
前段使用quick_form渲染
{{ wtf.quick_form(form) }}
2、尝试:考虑过直接在类属性声明中添加,但提示Job.query.all()没有绑定,查过stackover,不能在form申明时进行查询,好像此路不通
#app.order.forms.py
class EmployeeForm(Form):
projectIdentifier = StringField('项目编号', validators=[
DataRequired('请输入项目编号'),
Length(min=4, max=25, message='length must between 4 and 25')
])
submit = ButtonField('确定')
for job in Job.query.all():
vasr()[job.name]=SelectField(job.label, coerce=int)
def __init__(self, *args, **kwargs):
super(EmployeeForm, self).__init__(*args, **kwargs)
for job in Job.query.all():
getattr(self, job.name).choices = [(user.id, user.username) for user in User.query.all()]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论