【问题标题】:How to dynamically fill a selectbox / dropdownbox in a form using web.py?如何使用 web.py 在表单中动态填充选择框/下拉框?
【发布时间】:2011-01-14 23:37:55
【问题描述】:

所有 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)

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

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

【问题讨论】:

    标签: python forms web.py


    【解决方案1】:

    您可以通过将空列表传递给form.Dropdown args 来声明表单,然后在您的代码中设置args

    # form declaration
    MyForm = form.Form(form.Dropdown("french", []))
    
    # then in your controller
    my_form = MyForm()
    my_form.french.args = ['mustard', 'fries', 'wine']
    

    另外请不要使用form 作为变量,因为名称与web.form 冲突。

    【讨论】:

      【解决方案2】:

      我知道这是不久前发布的,但我是通过在之后设置值来做到这一点的,如下所示:

      form = input_form()
      form.get('some_input').value = _id
      return render.some_template(form)
      

      如果您愿意,这也允许您使用内置验证。我最终在板上找到了一个这样的例子,所以它可能有点隐藏文档。

      【讨论】:

        【解决方案3】:

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

        # Create copy of the form
        form = myform()
        
        # Append the dropdown to the form elements.
        form.inputs = tuple(list(form.inputs) + [mydropdown])
        

        【讨论】:

        • 我认为在这种情况下修补表单的输入并不好(但在其他情况下可能会很方便)。对于这种特殊情况,我建议使用args=[] 创建Dropdown,然后在表单的副本中设置下拉列表的args
        猜你喜欢
        • 2014-01-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-13
        • 2011-12-09
        • 1970-01-01
        • 1970-01-01
        • 2014-09-17
        相关资源
        最近更新 更多