我使用的是最新版本的flask、wtforms和Flask-WTForms。
我有一个显示表单的页面,其中一个是带有名为"A“的选项的选择框。
当应用程序启动时,一切都很好。在另一个表单中,我添加了一个名为"B“的记录。
现在,我想要的表单应该有选项A和B的选择框,只有选项A可用。我必须终止uWSGI并重启以获得刷新数据的wtforms。
那么,我错过了什么?如何让wtforms刷新数据?
下面是如何创建表单,其中getAgencyList返回要添加到选择框中的选项列表。在另一个对话中,我添加了一个代理,代理列表应该会更新,而不必重新启动应用程序:
class createUser(Form):
"""
Users are given a default password
"""
first_name = TextField()
last_name = TextField()
email = TextField('Email', [validators.Length(min=6, max=120), validators.Email()])
user_role = SelectField(u'User Role', choices=[('1', 'User'), ('2', 'Admin')])
org_role = SelectField(u'User Role', choices=[('1', 'Agency'), ('2', 'Advertiser'),('3', 'Admin')])
agency = SelectField(u'Agency', choices=getAgencyList())发布于 2012-08-29 16:07:45
问题是getAgencyList()是在定义类时调用的。所以无论那个函数在那个时候返回什么,都是它的数据。为了更新列表信息,您必须在实例化期间以某种方式运行getAgencyList。为此,您可以使用关于wtforms的一个不太明显的事实,该事实允许您向特定字段添加选项。documentation is here只查找标题为“使用动态选择值选择字段”的小节。下面是一个应该可以工作的代码示例。
class CreateUserForm(Form):
first_name = TextField()
last_name = TextField()
email = TextField('Email',
[validators.Length(min=6, max=120), validators.Email()])
user_role = SelectField(u'User Role',
choices=[('1', 'User'), ('2', 'Admin')])
org_role = SelectField(u'User Role',
choices=[('1', 'Agency'), ('2', 'Advertiser'),('3', 'Admin')])
agency = SelectField(u'Agency')
@classmethod
def new(cls):
# Instantiate the form
form = cls()
# Update the choices for the agency field
form.agency.choices = getAgencyList()
return form
# So in order to use you do this ...
@app.route('/someendpoint')
def some_flask_endpoint():
# ... some code ...
form = CreateUserForm.new()
# That should give you a working CreateUserForm with updated values.
# ... some more code to validate form probably...发布于 2016-01-26 08:04:39
一个简单的解决方案是从数据库获取要显示的选项,然后用这些选项覆盖Form Class:
例如:
def get_agencies():
agency_list = []
# get the Agencies from the database - syntax here would be SQLAlchemy
agencies = Agency.query.all()
for a in agencies:
# generate a new list of tuples
agency_list.append((a.id,a.name))
return agency_list
@app.route('/somewhere',methods=['POST'])
def somewhere():
form = createUser()
# overwrite the choices of the Form Class
form.agency.choices = get_agencies()
# here goes the rest of code - like form.validate_on_submit()
...
return render_template('create_user.html', form=form)https://stackoverflow.com/questions/12170995
复制相似问题