File: widgets.py

package info (click to toggle)
wtforms-components 0.11.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 352 kB
  • sloc: python: 1,582; makefile: 135; sh: 11
file content (295 lines) | stat: -rw-r--r-- 6,967 bytes parent folder | download
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
from copy import copy

from markupsafe import Markup, escape
from wtforms.validators import DataRequired, NumberRange
from wtforms.widgets import Input, html_params
from wtforms.widgets import Select as _Select

from .validators import DateRange, TimeRange


def min_max(field, validator_class):
    """
    Returns maximum minimum and minimum maximum value for given validator class
    of given field.

    :param field: WTForms Field object
    :param validator_class: WTForms Validator class

    Example::


        class MyForm(Form):
            some_integer_field = IntegerField(
                validators=[Length(min=3, max=6), Length(min=4, max=7)]
            )

        form = MyForm()

        min_max(form.some_integer_field, Length)
        # {'min': 4, 'max': 6}
    """
    min_values = []
    max_values = []
    for validator in field.validators:
        if isinstance(validator, validator_class):
            if validator.min is not None:
                min_values.append(validator.min)
            if validator.max is not None:
                max_values.append(validator.max)

    data = {}
    if min_values:
        data["min"] = max(min_values)
    if max_values:
        data["max"] = min(max_values)
    return data


def has_validator(field, validator_class):
    """
    Returns whether or not given field has an instance of given validator class
    in the validators property.

    :param field: WTForms Field object
    :param validator_class: WTForms Validator class
    """
    return any(
        [isinstance(validator, validator_class) for validator in field.validators]
    )


class HTML5Input(Input):
    validation_attrs = ["required", "disabled"]

    def __init__(self, **kwargs):
        self.options = kwargs

    def __call__(self, field, **kwargs):
        if has_validator(field, DataRequired):
            kwargs.setdefault("required", True)

        for key, value in self.range_validators(field).items():
            kwargs.setdefault(key, value)

        if hasattr(field, "widget_options"):
            for key, value in self.field.widget_options:
                kwargs.setdefault(key, value)

        options_copy = copy(self.options)
        options_copy.update(kwargs)
        return super().__call__(field, **options_copy)

    def range_validators(self, field):
        return {}


class BaseDateTimeInput(HTML5Input):
    """
    Base class for TimeInput, DateTimeLocalInput, DateTimeInput and
    DateInput widgets
    """

    range_validator_class = DateRange

    def range_validators(self, field):
        data = min_max(field, self.range_validator_class)
        if "min" in data:
            data["min"] = data["min"].strftime(self.format)
        if "max" in data:
            data["max"] = data["max"].strftime(self.format)
        return data


class TextInput(HTML5Input):
    input_type = "text"


class SearchInput(HTML5Input):
    """
    Renders an input with type "search".
    """

    input_type = "search"


class MonthInput(HTML5Input):
    """
    Renders an input with type "month".
    """

    input_type = "month"


class WeekInput(HTML5Input):
    """
    Renders an input with type "week".
    """

    input_type = "week"


class RangeInput(HTML5Input):
    """
    Renders an input with type "range".
    """

    input_type = "range"


class URLInput(HTML5Input):
    """
    Renders an input with type "url".
    """

    input_type = "url"


class ColorInput(HTML5Input):
    """
    Renders an input with type "color".
    """

    input_type = "color"


class TelInput(HTML5Input):
    """
    Renders an input with type "tel".
    """

    input_type = "tel"


class EmailInput(HTML5Input):
    """
    Renders an input with type "email".
    """

    input_type = "email"


class TimeInput(BaseDateTimeInput):
    """
    Renders an input with type "time".

    Adds min and max html5 field parameters based on field's TimeRange
    validator.
    """

    input_type = "time"
    range_validator_class = TimeRange
    format = "%H:%M:%S"


class DateTimeLocalInput(BaseDateTimeInput):
    """
    Renders an input with type "datetime-local".

    Adds min and max html5 field parameters based on field's DateRange
    validator.
    """

    input_type = "datetime-local"
    format = "%Y-%m-%dT%H:%M:%S"


class DateTimeInput(BaseDateTimeInput):
    """
    Renders an input with type "datetime".

    Adds min and max html5 field parameters based on field's DateRange
    validator.
    """

    input_type = "datetime"
    format = "%Y-%m-%dT%H:%M:%SZ"


class DateInput(BaseDateTimeInput):
    """
    Renders an input with type "date".

    Adds min and max html5 field parameters based on field's DateRange
    validator.
    """

    input_type = "date"
    format = "%Y-%m-%d"


class NumberInput(HTML5Input):
    """
    Renders an input with type "number".

    Adds min and max html5 field parameters based on field's NumberRange
    validator.
    """

    input_type = "number"
    range_validator_class = NumberRange

    def range_validators(self, field):
        return min_max(field, self.range_validator_class)


class ReadOnlyWidgetProxy:
    def __init__(self, widget):
        self.widget = widget

    def __getattr__(self, name):
        return getattr(self.widget, name)

    def __call__(self, field, **kwargs):
        kwargs.setdefault("readonly", True)
        # Some html elements also need disabled attribute to achieve the
        # expected UI behaviour.
        kwargs.setdefault("disabled", True)
        return self.widget(field, **kwargs)


class SelectWidget(_Select):
    """
    Add support of choices with ``optgroup`` to the ``Select`` widget.
    """

    @classmethod
    def render_optgroup(cls, value, label, mixed):
        children = []

        for item_value, item_label in label:
            item_html = cls.render_option(item_value, item_label, mixed)
            children.append(item_html)

        html = '<optgroup label="%s">%s</optgroup>'
        data = (escape(str(value)), "\n".join(children))
        return Markup(html % data)

    @classmethod
    def render_option(cls, value, label, mixed):
        """
        Render option as HTML tag, but not forget to wrap options into
        ``optgroup`` tag if ``label`` var is ``list`` or ``tuple``.
        """
        if isinstance(label, (list, tuple)):
            return cls.render_optgroup(value, label, mixed)

        try:
            coerce_func, data = mixed
        except TypeError:
            selected = mixed
        else:
            if isinstance(data, list) or isinstance(data, tuple):
                selected = coerce_func(value) in data
            else:
                selected = coerce_func(value) == data

        options = {"value": value}

        if selected:
            options["selected"] = True

        html = "<option %s>%s</option>"
        data = (html_params(**options), escape(str(label)))

        return Markup(html % data)