【发布时间】:2016-02-20 13:33:57
【问题描述】:
我在表单域的简单渲染上苦苦挣扎了将近一天。如果你能在这方面帮助我,那就太好了。
我正在使用 Flask-WTF,python 2.7。
我正在尝试使用自定义 ListWidget 呈现 SelectField。该字段基本上必须在 UL HTML 标记中呈现,而不是 SELECT html 标记,这似乎是我正在努力解决的问题。
这就是我的自定义小部件类的样子:
widget.py
class CustomListWidget(ListWidget):
def __init__(self, *args, **kwargs):
super(CustomListWidget, self).__init__(*args, **kwargs)
def __call__(self, field, **kwargs):
kwargs.setdefault('id', field.id)
html = ['<{} {}>'.format(self.html_tag, html_params(**kwargs))]
for subfield in field:
html.append('<li><span>{}</span></li>'.format(subfield()))
html.append('</{}>'.format(self.html_tag))
return HTMLString(''.join(html))
这是我的表单的外观,而类别字段是我正在努力解决的问题。
form.py
from widget import CustomListWidget
from wtforms import SelectField, SubmitField
widget = CustomListWidget(html_tag='ul')
class MyForm(Form):
category = SelectField('category', [DataRequired()], widget=widget, default='1', choices=[
('1', 'whatever'),
('2', 'whatever2')
])
submit = SubmitField('Search')
view.py
from form import MyForm
from flask import render_template
@app.route('/formtest', methods=['GET', 'POST'])
def formtest():
form = MyForm()
if request.method == 'GET':
render_template('form.html', form=form)
if form.validate_on_submit():
return redirect(url_for('whatever', data=-form.data))
return 'form not validated'
form.html
<div class="search-input with-dropdown">
<div class="dropdown">
{{ form.category(class='dropdown-content hide') }} }}
</div>
</div>
使用此代码,我能够获得预期的显示,但没有从该字段传递任何值。无论我选择哪个值,我提交后,都只有默认值。
【问题讨论】:
标签: python flask jinja2 wtforms flask-wtforms