Created
April 9, 2012 17:22
-
-
Save jbclements/2344831 to your computer and use it in GitHub Desktop.
Excerpt from django forms/extras/widgets.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SelectDateWidget(Widget): | |
""" | |
A Widget that splits date input into three <select> boxes. | |
This also serves as an example of a Widget that has more than one HTML | |
element and hence implements value_from_datadict. | |
""" | |
none_value = (0, '---') | |
month_field = '%s_month' | |
day_field = '%s_day' | |
year_field = '%s_year' | |
def __init__(self, attrs=None, years=None, required=True): | |
# years is an optional list/tuple of years to use in the "year" select box. | |
self.attrs = attrs or {} | |
self.required = required | |
if years: | |
self.years = years | |
else: | |
this_year = datetime.date.today().year | |
self.years = range(this_year, this_year+10) | |
def render(self, name, value, attrs=None): | |
try: | |
year_val, month_val, day_val = value.year, value.month, value.day | |
except AttributeError: | |
year_val = month_val = day_val = None | |
if isinstance(value, basestring): | |
if settings.USE_L10N: | |
try: | |
input_format = get_format('DATE_INPUT_FORMATS')[0] | |
v = datetime.datetime.strptime(value, input_format) | |
year_val, month_val, day_val = v.year, v.month, v.day | |
except ValueError: | |
pass | |
else: | |
match = RE_DATE.match(value) | |
if match: | |
year_val, month_val, day_val = [int(v) for v in match.groups()] | |
choices = [(i, i) for i in self.years] | |
year_html = self.create_select(name, self.year_field, value, year_val, choices) | |
choices = MONTHS.items() | |
month_html = self.create_select(name, self.month_field, value, month_val, choices) | |
choices = [(i, i) for i in range(1, 32)] | |
day_html = self.create_select(name, self.day_field, value, day_val, choices) | |
output = [] | |
for field in _parse_date_fmt(): | |
if field == 'year': | |
output.append(year_html) | |
elif field == 'month': | |
output.append(month_html) | |
elif field == 'day': | |
output.append(day_html) | |
return mark_safe(u'\n'.join(output)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment