Ticket #16575: widgets.2.py

File widgets.2.py, 4.5 KB (added by foobarrior, 13 years ago)

the same, only removed pep8 utility's errors and warnings

Line 
1"""
2Extra HTML Widget classes
3"""
4
5import time
6import datetime
7import re
8
9from django.forms.widgets import Widget, Select
10from django.utils import datetime_safe
11from django.utils.dates import MONTHS
12from django.utils.safestring import mark_safe
13from django.utils.formats import get_format
14from django.conf import settings
15
16__all__ = ('SelectDateWidget',)
17
18RE_DATE = re.compile(r'(\d{4})-(\d\d?)-(\d\d?)$')
19
20
21def _parse_format(fmt):
22 def pos(s):
23 match = re.search('[' + s + ']', fmt)
24 return match.start() + 1 if match else 0
25
26 dic = {'day': pos('dj'), 'month': pos('bEFMmNn'), 'year': pos('yY')}
27 return sorted(filter(None, dic.keys()), key=dic.get)
28
29
30def _parse_date_fmt():
31 return _parse_format(re.subn(r'\\.', '', get_format('DATE_FORMAT'))[0])
32
33
34class SelectDateWidget(Widget):
35 """
36 A Widget that splits date input into three <select> boxes.
37
38 This also serves as an example of a Widget that has more than one HTML
39 element and hence implements value_from_datadict.
40 """
41 names = ('day', 'month', 'year',)
42 none_values_dafault = '---'
43 field_values = ['%s_' + n for n in names]
44 fields = dict(zip(names, field_values))
45 day_field, month_field, year_field = field_values
46
47 def __init__(self, attrs=None, years=None, required=True,
48 date_format='', none_values=None):
49 # years is an optional list/tuple of years
50 # to use in the "year" select box.
51 self.attrs = attrs or {}
52 self.required = required
53 if not years:
54 this_year = datetime.date.today().year
55 years = range(this_year, this_year + 10)
56 print list(years)
57 self.years = years
58 self.date_format = _parse_format(date_format)
59 self.none_values = none_values \
60 or dict([(i, self.none_values_dafault) for i in 'dmy'])
61
62 def render(self, name, value, attrs=None):
63
64 get_names_dict = lambda l: dict(zip(self.names, l))
65
66 try:
67 values_list = [getattr(value, n) for n in self.names]
68 except AttributeError:
69 values_list = []
70 if isinstance(value, basestring):
71 if settings.USE_L10N:
72 try:
73 input_format = get_format('DATE_INPUT_FORMATS')[0]
74 v = datetime.datetime.strptime(value, input_format)
75 values_list = [getattr(v, n) for n in self.names]
76 except ValueError:
77 pass
78 else:
79 match = RE_DATE.match(value)
80 if match:
81 values_list = (int(v) for v in match.groups())
82 values = get_names_dict(values_list)
83
84 choices = get_names_dict([
85 [(i, i) for i in range(1, 32)],
86 MONTHS.items(),
87 [(i, i) for i in self.years],
88 ])
89
90 create_select_short = lambda n: self.create_select(
91 name, self.fields[n], value, values.get(n), choices[n], n
92 )
93
94 htmls = get_names_dict([create_select_short(n) for n in self.names])
95
96 date_format = self.date_format or _parse_date_fmt()
97 output = [htmls[field] for field in date_format]
98 return mark_safe(u'\n'.join(output))
99
100 def id_for_label(cls, id_):
101 field_list = _parse_date_fmt()
102 if field_list:
103 first_select = field_list[0]
104 else:
105 first_select = 'month'
106 return '%s_%s' % (id_, first_select)
107 id_for_label = classmethod(id_for_label)
108
109 def value_from_datadict(self, data, files, name):
110 d, m, y = (data.get(self.fields[n] % name) for n in self.names)
111 if y == m == d == "0":
112 return None
113 if not (y and m and d):
114 return data.get(name)
115 if not settings.USE_L10N:
116 return '%s-%s-%s' % (y, m, d)
117 input_format = get_format('DATE_INPUT_FORMATS')[0]
118 try:
119 date_value = datetime.date(int(y), int(m), int(d))
120 date_value = datetime_safe.new_date(date_value)
121 return date_value.strftime(input_format)
122 except ValueError:
123 return '%s-%s-%s' % (y, m, d)
124
125 def create_select(self, name, field, value, val, choices, date_part='d'):
126 if 'id' in self.attrs:
127 id_ = self.attrs['id']
128 else:
129 id_ = 'id_%s' % name
130 if not (self.required and val):
131 choices.insert(0, (0, self.none_values[date_part[0]]))
132 local_attrs = self.build_attrs(id=field % id_)
133 s = Select(choices=choices)
134 select_html = s.render(field % name, val, local_attrs)
135 return select_html
136
Back to Top