我认为 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()
和模板/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>