2
Extra HTML Widget classes
5
from django.newforms.widgets import Widget, Select
6
from django.utils.dates import MONTHS
9
__all__ = ('SelectDateWidget',)
11
class SelectDateWidget(Widget):
13
A Widget that splits date input into three <select> boxes.
15
This also serves as an example of a Widget that has more than one HTML
16
element and hence implements value_from_datadict.
18
month_field = '%s_month'
20
year_field = '%s_year'
22
def __init__(self, attrs=None, years=None):
23
# years is an optional list/tuple of years to use in the "year" select box.
24
self.attrs = attrs or {}
28
this_year = datetime.date.today().year
29
self.years = range(this_year, this_year+10)
31
def render(self, name, value, attrs=None):
33
value = datetime.date(*map(int, value.split('-')))
34
year_val, month_val, day_val = value.year, value.month, value.day
35
except (AttributeError, TypeError, ValueError):
36
year_val = month_val = day_val = None
40
month_choices = MONTHS.items()
42
select_html = Select(choices=month_choices).render(self.month_field % name, month_val)
43
output.append(select_html)
45
day_choices = [(i, i) for i in range(1, 32)]
46
select_html = Select(choices=day_choices).render(self.day_field % name, day_val)
47
output.append(select_html)
49
year_choices = [(i, i) for i in self.years]
50
select_html = Select(choices=year_choices).render(self.year_field % name, year_val)
51
output.append(select_html)
53
return u'\n'.join(output)
55
def value_from_datadict(self, data, name):
56
y, m, d = data.get(self.year_field % name), data.get(self.month_field % name), data.get(self.day_field % name)
58
return '%s-%s-%s' % (y, m, d)