如何使用web.py动态填充表单中的选择框/下拉框?

ram*_*yne 6 python forms web.py

所有web.py表单示例都采用以下格式(来自webpy.org):

myform = form.Form( 
    form.Textbox("boe"), 
    form.Textbox("bax", 
        form.notnull,
        form.regexp('\d+', 'Must be a digit'),
        form.Validator('Must be more than 5', lambda x:int(x)>5)),
    form.Textarea('moe'),
    form.Checkbox('curly'), 
    form.Dropdown('french', ['mustard', 'fries', 'wine'])) 

class index: 
    def GET(self): 
        form = myform()
        # make sure you create a copy of the form by calling it (line above)
        # Otherwise changes will appear globally
        return render.formtest(form)

    def POST(self): 
        form = myform() 
        if not form.validates(): 
            return render.formtest(form)
        else:
            # form.d.boe and form['boe'].value are equivalent ways of
            # extracting the validated arguments from the form.
            return "Grrreat success! boe: %s, bax: %s" % (form.d.boe, form['bax'].value)
Run Code Online (Sandbox Code Playgroud)

我不希望在声明表单时填充下拉框(上例中的form.Dropdown)静态,但是在GET/POST方法中使用在调用页面时从数据库表中检索的条目.

我已搜索了几个小时但无法在任何地方找到提示(google,webpy.org,google groups)

Try*_*yPy 2

我建议您创建其他元素和表单,然后在 GET/POST 中根据需要创建下拉元素,然后:

# Create copy of the form
form = myform()

# Append the dropdown to the form elements.
form.inputs = tuple(list(form.inputs) + [mydropdown])
Run Code Online (Sandbox Code Playgroud)

  • 我认为在这种情况下修补表单的输入并不好(但在其他情况下可能很方便)。对于这种特殊情况,我建议使用“args=[]”创建“Dropdown”,然后在表单的副本中设置下拉列表的“args”。 (2认同)