-
Notifications
You must be signed in to change notification settings - Fork 7
/
wtforms_widgets.py
330 lines (246 loc) · 10.1 KB
/
wtforms_widgets.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
from wtforms.widgets.core import FileInput, Input, PasswordInput, Select, SubmitInput, TextArea, TextInput
from govuk_frontend_wtf.gov_form_base import GovFormBase, GovIterableBase
"""Lifted from WTForms and modified to generate GOV.UK markup
The upstream code should be monitored when updating WTForms to
see if any modifications need to be brought in
"""
class GovInput(GovFormBase, Input):
"""Render a basic ``<input>`` field.
This is used as the basis for most of the other input fields.
By default, the `_value()` method will be called upon the associated field
to provide the ``value=`` HTML attribute.
"""
template = "govuk_frontend_wtf/input.html"
def __call__(self, field, **kwargs):
kwargs.setdefault("id", field.id)
kwargs.setdefault("type", self.input_type)
if "value" not in kwargs:
kwargs["value"] = field._value()
if "required" not in kwargs and "required" in getattr(field, "flags", []):
kwargs["required"] = True
return super().__call__(field, **kwargs)
class GovTextInput(GovInput, TextInput):
"""Render a single-line text input."""
input_type = "text"
class GovPasswordInput(GovInput, PasswordInput):
"""Render a password input.
For security purposes, this field will not reproduce the value on a form
submit by default. To have the value filled in, set `hide_value` to
`False`.
"""
def __call__(self, field, **kwargs):
if self.hide_value:
kwargs["value"] = ""
return super().__call__(field, **kwargs)
class GovCheckboxesInput(GovIterableBase):
"""Multiple checkboxes, from a SelectMultipleField
This widget type doesn't exist in WTForms - the recommendation
there is to use a combination of the list and checkbox widgets.
However in the GOV.UK macros this type of field is not simply
a list of smaller widgets - multiple checkboxes are a single
construct of their own.
"""
template = "govuk_frontend_wtf/checkboxes.html"
input_type = "checkbox"
def map_gov_params(self, field, **kwargs):
params = super().map_gov_params(field, **kwargs)
params.setdefault(
"fieldset",
{
"legend": {
"text": field.label.text,
},
},
)
return params
class GovCheckboxInput(GovCheckboxesInput):
"""Render a single checkbox (i.e. a WTForms BooleanField)."""
def __call__(self, field, **kwargs):
# We are subclassing GovCheckboxesInput which expects
# the field to be an iterable yielding each checkbox "subfield"
# In order to make our single BooleanField comply with this, we
# need to provide it with a similar construct, but which only
# yields a single checkbox
class IterableField(object):
def __init__(self, field):
self.field = field
self.max = 1
def __iter__(self):
self.index = 0
return self
def __next__(self):
if self.index < self.max:
self.index += 1
return self.field
else:
raise StopIteration
def __getattr__(self, name):
return getattr(self.field, name)
field_group = IterableField(field)
return super().__call__(field_group, **kwargs)
def map_gov_params(self, field, **kwargs):
params = super().map_gov_params(field, **kwargs)
params.pop("fieldset")
return params
class GovRadioInput(GovIterableBase):
"""Render radio button inputs.
Uses the field label as the fieldset legend.
"""
template = "govuk_frontend_wtf/radios.html"
input_type = "radio"
def map_gov_params(self, field, **kwargs):
params = super().map_gov_params(field, **kwargs)
params.setdefault(
"fieldset",
{
"legend": {"text": field.label.text},
},
)
return params
class GovDateInput(GovFormBase):
"""Renders three input fields representing Day, Month and Year.
To be used as a widget for WTForms' DateField or DateTimeField.
The input field labels are hardcoded to "Day", "Month" and "Year".
The provided label is set as a legend above the input fields.
The field names MUST all be the same for this widget to work.
"""
template = "govuk_frontend_wtf/date.html"
def __call__(self, field, **kwargs):
kwargs.setdefault("id", field.id)
if "value" not in kwargs:
kwargs["value"] = field._value()
if "required" not in kwargs and "required" in getattr(field, "flags", []):
kwargs["required"] = True
return super().__call__(field, **kwargs)
def map_gov_params(self, field, **kwargs):
params = super().map_gov_params(field, **kwargs)
day, month, year = [None] * 3
if field.raw_data is not None:
day, month, year = field.raw_data
elif field.data:
day, month, year = field.data.strftime("%d %m %Y").split(" ")
params.setdefault(
"fieldset",
{
"legend": {"text": field.label.text},
},
)
params.setdefault(
"items",
[
{
"label": "Day",
"id": "{}-day".format(field.name),
"name": field.name,
"classes": " ".join(
[
"govuk-input--width-2",
"govuk-input--error" if field.errors else "",
]
).strip(),
"value": day,
},
{
"label": "Month",
"id": "{}-month".format(field.name),
"name": field.name,
"classes": " ".join(
[
"govuk-input--width-2",
"govuk-input--error" if field.errors else "",
]
).strip(),
"value": month,
},
{
"label": "Year",
"id": "{}-year".format(field.name),
"name": field.name,
"classes": " ".join(
[
"govuk-input--width-4",
"govuk-input--error" if field.errors else "",
]
).strip(),
"value": year,
},
],
)
return params
class GovFileInput(GovInput, FileInput):
"""Render a file chooser input.
:param multiple: allow choosing multiple files
"""
template = "govuk_frontend_wtf/file-upload.html"
def __call__(self, field, **kwargs):
# browser ignores value of file input for security
kwargs["value"] = False
if self.multiple:
kwargs["multiple"] = True
return super().__call__(field, **kwargs)
class GovSubmitInput(GovInput, SubmitInput):
"""Renders a submit button.
The field's label is used as the text of the submit button instead of the
data on the field.
"""
template = "govuk_frontend_wtf/button.html"
def __call__(self, field, **kwargs):
return super().__call__(field, **kwargs)
def map_gov_params(self, field, **kwargs):
params = super().map_gov_params(field, **kwargs)
params.setdefault("text", field.label.text)
params.setdefault("element", "button")
return params
class GovTextArea(GovFormBase, TextArea):
"""Renders a multi-line text area.
`rows` and `cols` ought to be passed as keyword args when rendering.
"""
template = "govuk_frontend_wtf/textarea.html"
def __call__(self, field, **kwargs):
kwargs.setdefault("id", field.id)
if "value" not in kwargs:
kwargs["value"] = field._value()
if "required" not in kwargs and "required" in getattr(field, "flags", []):
kwargs["required"] = True
return super().__call__(field, **kwargs)
class GovCharacterCount(GovFormBase, TextArea):
"""Renders a multi-line text area with a character count.
`rows` and `cols` ought to be passed as keyword args when rendering.
"""
template = "govuk_frontend_wtf/charactercount.html"
def __call__(self, field, **kwargs):
kwargs.setdefault("id", field.id)
if "value" not in kwargs:
kwargs["value"] = field._value()
if "required" not in kwargs and "required" in getattr(field, "flags", []):
kwargs["required"] = True
return super().__call__(field, **kwargs)
class GovSelect(GovFormBase, Select):
"""Renders a select field.
If `multiple` is True, then the `size` property should be specified on
rendering to make the field useful.
The field must provide an `iter_choices()` method which the widget will
call on rendering; this method must yield tuples of
`(value, label, selected)`.
"""
template = "govuk_frontend_wtf/select.html"
def __call__(self, field, **kwargs):
if self.multiple:
raise Exception(
"Please do not render mutliselect elements as a select box"
" - you should use checkboxes instead in order to comply with"
" the GOV.UK service manual"
)
kwargs.setdefault("id", field.id)
if "required" not in kwargs and "required" in getattr(field, "flags", []):
kwargs["required"] = True
kwargs["items"] = []
# Construct select box choices
for val, label, selected in field.iter_choices():
item = {"text": label, "value": val, "selected": selected}
kwargs["items"].append(item)
return super().__call__(field, **kwargs)
def map_gov_params(self, field, **kwargs):
params = super().map_gov_params(field, **kwargs)
params["items"] = kwargs["items"]
return params