gpt4 book ai didi

python - Flask 和 WTForms - 如何让 wtforms 刷新选择的数据

转载 作者:太空狗 更新时间:2023-10-29 20:56:44 26 4
gpt4 key购买 nike

我使用的是最新版本的 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())

最佳答案

问题是 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...

关于python - Flask 和 WTForms - 如何让 wtforms 刷新选择的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12170995/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com