我正在寻找最简单、最干净的方法来呈现具有 3 个选择的基本 DateField。
<select>day</select><select>month</select><select>year</select>
(如果可能,使用“格式”来选择如何显示最终渲染)
最佳答案
您可以利用 DateField 将处理多值输入并用空格将它们连接在一起这一事实,这样您就可以避免使用次要形式,而只是提供一系列输入:
from wtforms.widgets.core import Select, HTMLString, html_params
class SelectDateWidget(object):
FORMAT_CHOICES = {
'%d': [(x, str(x)) for x in range(1, 32)],
'%m': [(x, str(x)) for x in range(1, 13)],
'%y': [(x, str(x)) for x in range(1950, 2014)],
}
def __call__(self, field, **kwargs):
field_id = kwargs.pop('id', field.id)
html = []
for format in field.format.split():
choices = self.FORMAT_CHOICES[format]
id_suffix = format.replace('%', '-')
params = dict(kwargs, name=field.name, id=field_id + id_suffix)
html.append('<select %s>' % html_params(params))
if field.data:
current_value = int(field.data.strftime(format))
else:
current_value = None
for value, label in choices:
selected = (value == current_value)
html.append(Select.render_option(value, label, selected))
html.append('</select>')
return HTMLString(''.join(html))
# Usage
class MyForm(Form):
american_date = DateField(format='%m %d %y', widget=SelectDateWidget())
european_date = DateField(format='%d %m %y', widget=SelectDateWidget())
关于python - 如何用 3 个选择渲染 DateField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14643200/