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



我使用的是最新版本的烧瓶、wtforms和烧瓶wtforms。

我有一个显示表格的页面,其中一个是一个带有选项"a"的选择框。

当应用程序启动时,一切都很好。在另一种形式中,我添加了一个名为"B"的记录。

现在,我想要的表单应该有选择框,选项A和B只有机器人选项A可用。我必须杀死uWSGI并重新启动以获取wtforms来刷新数据。

那么,我错过了什么?如何获取wtforms来刷新数据?

以下是我创建表单的方法,其中getAgentList返回要添加到选择框中的选项列表。在另一个对话中,我添加了一个代理,代理列表应该在不必重新启动应用程序的情况下更新:

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的不太明显的事实,该事实允许您向特定字段添加选项。这里的文档只是查找标题为"选择具有动态选择值的字段"的小节。下面是一个应该可以工作的代码示例。

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...

一个简单的解决方案是从数据库中获取要显示的选项,然后用以下选项覆盖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)

最新更新