wtforms.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. # -*- coding: utf-8 -*-
  2. """
  3. flaskbb.utils.wtforms
  4. ~~~~~~~~~~~~~~~~~~~~
  5. Additional widgets for wtforms
  6. :copyright: (c) 2013 by the FlaskBB Team.
  7. :license: BSD, see LICENSE for more details.
  8. """
  9. from datetime import datetime
  10. from wtforms.widgets.core import Select, HTMLString, html_params
  11. class SelectDateWidget(object):
  12. """
  13. Renders a DateTime field with 3 selects.
  14. For more information see: http://stackoverflow.com/a/14664504
  15. """
  16. FORMAT_CHOICES = {
  17. '%d': [(x, str(x)) for x in range(1, 32)],
  18. '%m': [(x, str(x)) for x in range(1, 13)]
  19. }
  20. FORMAT_CLASSES = {
  21. '%d': 'select_date_day',
  22. '%m': 'select_date_month',
  23. '%Y': 'select_date_year'
  24. }
  25. def __init__(self, years=range(1930, datetime.utcnow().year+1)):
  26. super(SelectDateWidget, self).__init__()
  27. self.FORMAT_CHOICES['%Y'] = [(x, str(x)) for x in years]
  28. def __call__(self, field, **kwargs):
  29. field_id = kwargs.pop('id', field.id)
  30. html = []
  31. allowed_format = ['%d', '%m', '%Y']
  32. for format in field.format.split():
  33. if (format in allowed_format):
  34. choices = self.FORMAT_CHOICES[format]
  35. id_suffix = format.replace('%', '-')
  36. id_current = field_id + id_suffix
  37. kwargs['class'] = self.FORMAT_CLASSES[format]
  38. try:
  39. del kwargs['placeholder']
  40. except:
  41. pass
  42. html.append('<select %s>' % html_params(name=field.name,
  43. id=id_current,
  44. **kwargs))
  45. if field.data:
  46. current_value = int(field.data.strftime(format))
  47. else:
  48. current_value = None
  49. for value, label in choices:
  50. selected = (value == current_value)
  51. html.append(Select.render_option(value, label, selected))
  52. html.append('</select>')
  53. else:
  54. html.append(format)
  55. html.append(
  56. """<input type="hidden" value="{}" {}></input>""".format(
  57. html_params(name=field.name, id=id_current, **kwargs)))
  58. html.append(' ')
  59. return HTMLString(''.join(html))