如何使用Flask/WTForms预先填充复选框

Eri*_*son 7 python flask wtforms

我正在尝试生成一个动态复选框列表,其中根据数据状态检查某些框.

这是我的表格:

class FooForm(Form):
    bar = SelectMultipleField(
        'Bar',
        option_widget=CheckboxInput(),
        widget=ListWidget(prefix_label=True))
Run Code Online (Sandbox Code Playgroud)

这是控制器:

@app.route('/fooform', methods = ['GET','POST'])
def foo():
    foos = foo_dao.find() 
    form = FooForm()
    form.bar.choices = [(foo.id, foo.label) for foo in foos]
    # SOMEHOW PRE-POPULATE CHECKBOXES HERE
    if form.is_submitted():
        # DO STUFF
    return render_template('foo.html', 
                           foos=foos,
                           form=form)
Run Code Online (Sandbox Code Playgroud)

这是模板:

  <form action="" method="post" name="foos">
      {{form.bar}}
    <p><input type="submit" value="Add"></p>
  </form>
Run Code Online (Sandbox Code Playgroud)

这会生成一个复选框列表,但它可以工作,但我无法弄清楚如何指定列表中的哪些复选框要预先填充.

nsf*_*n55 5

使用的组合FormFieldFieldList:对于额外的锅炉板一点点的费用和一些手在持续时间结合,你可以打破你的提交到多个领域得到了类似的结果。

从一个这样做的好处的方法来WTForms。如果坚持下去,您会发现表格工作更顺畅。这是因为您正在使用库中内置的默认行为。尽管该库允许您混合和匹配Widget类,但根据我的经验,只有很少的组合子集可以很好地协同工作。如果您坚持使用基本的Field/ Validator组合并将其与FormField/ 组合在一起,则FieldList效果会更好。

请参阅以下示例:

from collections import namedtuple
from wtforms import Form, FieldList, BooleanField, HiddenField, FormField
from webob.multidict import MultiDict

GroceryItem = namedtuple('GroceryItem', ['item_id', 'want', 'name'])

class GroceryItemForm(Form):
    item_id = HiddenField()
    want = BooleanField()

class GroceryListForm(Form):
    def __init__(self, *args, **kwargs):
        super(GroceryListForm, self).__init__(*args, **kwargs)

        # just a little trickery to get custom labels
        # on the list's checkboxes
        for item_form in self.items:
            for item in kwargs['data']['items']:
                if item.item_id == item_form.item_id.data:
                    item_form.want.label ='' 
                    item_form.label = item.name

    items = FieldList(FormField(GroceryItemForm))

item1 = GroceryItem(1, True, 'carrots')
item2 = GroceryItem(2, False, 'cornmeal')

data = {'items': [item1, item2]}

form = GroceryListForm(data=MultiDict(data))

print form.items()
Run Code Online (Sandbox Code Playgroud)

原始HTML

<ul id="items">
   <li>
      carrots 
      <table id="items-0">
         <tr>
            <th></th>
            <td><input id="items-0-item_id
               " name="items-0-item_id" type="hidden" value="1"><input checked id="items-0-want" name="it
               ems-0-want" type="checkbox" value="y"></td>
         </tr>
      </table>
   </li>
   <li>
      cornmeal 
      <table id="items
         -1">
      <tr>
         <th></th>
         <td><input id="items-1-item_id" name="items-1-item_id" type="hidden" valu
            e="2"><input id="items-1-want" name="items-1-want" type="checkbox" value="y"></td>
      </tr>
      </t
      able>
   </li>
</ul>
Run Code Online (Sandbox Code Playgroud)

渲染结果

在此处输入图片说明

form.data开机自检后的结果

{'items': [{'item_id': 1, 'want': True}, {'item_id': 2, 'want': False}]}


小智 5

我认为 jeverling 的答案非常接近,并引导我找到了经过测试的解决方案。我需要项目保持选中状态,但每次 url 被服务时,复选框项目都会被清除,除非您可以指定选择。

重要的部分是 ChoiceObj(上面是 MyObj)从 object 继承,以便可以在其上调用 setattr。为了使这项工作, setattr(obj, attribute, value) 的参数在哪里

  • obj 是 ChoiceObj 实例
  • 属性是表单的名称
  • 在选项列表中设置的值。

颜色.py:

from flask.ext.wtf import Form
from flask import Flask, render_template, session, redirect, url_for
from wtforms import SelectMultipleField, SubmitField, widgets

SECRET_KEY = 'development'

app = Flask(__name__)
app.config.from_object(__name__)

class ChoiceObj(object):
    def __init__(self, name, choices):
        # this is needed so that BaseForm.process will accept the object for the named form,
        # and eventually it will end up in SelectMultipleField.process_data and get assigned
        # to .data
        setattr(self, name, choices)

class MultiCheckboxField(SelectMultipleField):
    widget = widgets.TableWidget()
    option_widget = widgets.CheckboxInput()

    # uncomment to see how the process call passes through this object
    # def process_data(self, value):
    #     return super(MultiCheckboxField, self).process_data(value)

class ColorLookupForm(Form):
    submit = SubmitField('Save')
    colors = MultiCheckboxField(None)

allColors = ( 'red', 'pink', 'blue', 'green', 'yellow', 'purple' )

@app.route('/', methods=['GET', 'POST'])
def color():
    selectedChoices = ChoiceObj('colors', session.get('selected') )
    form = ColorLookupForm(obj=selectedChoices)
    form.colors.choices =  [(c, c) for c in allColors]

    if form.validate_on_submit():
        session['selected'] = form.colors.data
        return redirect(url_for('.color'))
    else:
        print form.errors
    return render_template('color.html',
                           form=form,
                           selected=session.get('selected'))

if __name__ == '__main__':
    app.run()
Run Code Online (Sandbox Code Playgroud)

和模板/color.html

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <form method="post">
        <table>
            <tr>
                <td>
                    {{ form.hidden_tag() }}
                    {{ form.colors }}
                </td>
                <td width="20"></td>
                <td>
                    <b>Selected</b><br>
                    {% for s in selected %}
                        {{ s }}<br>
                    {% endfor %}
                </td>
            </tr>

        </table>
        <input type="submit">
    </form>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)


jev*_*ing 2

我认为使用内部子类的方法应该可以解决这个问题:

http://wtforms.simplecodes.com/docs/1.0.1/special_problems.html#dynamic-form-composition

您必须在初始化表单之前设置选择,您可以使用内部子类来完成此操作。然后,您可以将一个对象传递给表单,wtforms 将使用该对象来预填充您的字段:

def foo():
    class F(FooForm):
        pass
    choices = [(foo.id, foo.label) for foo in foos]
    F.bar.choices = choices

    class MyObj(object):
        pass
    obj = MyObj()
    for choice in choices:
        setattr(obj, choice, True)

    form = F(request.POST or None, obj=obj)
Run Code Online (Sandbox Code Playgroud)

请注意,这尚未经过测试,但我认为它应该有效。
祝你好运!