Debian Codegraph @

django_filters/fields.py

raw
1 from collections import namedtuple
2 from datetime import datetime, time
3
4 from django import forms
5 from django.utils.dateparse import parse_datetime
6 from django.utils.encoding import force_str
7 from django.utils.translation import gettext_lazy as _
8
9 from .conf import settings
10 from .constants import EMPTY_VALUES
11 from .utils import handle_timezone
12 from .widgets import (
13 BaseCSVWidget,
14 CSVWidget,
15 DateRangeWidget,
16 LookupChoiceWidget,
17 RangeWidget,
18 )
19
20 try:
21 from django.utils.choices import BaseChoiceIterator, normalize_choices
22 except ImportError:
23 DJANGO_50 = False
24 else:
25 DJANGO_50 = True
26
27
28 class RangeField(forms.MultiValueField):
29 widget = RangeWidget
30
31 def __init__(self, fields=None, *args, **kwargs):
32 if fields is None:
33 fields = (forms.DecimalField(), forms.DecimalField())
34 super().__init__(fields, *args, **kwargs)
35
36 def compress(self, data_list):
37 if data_list:
38 return slice(*data_list)
39 return None
40
41
42 class DateRangeField(RangeField):
43 widget = DateRangeWidget
44
45 def __init__(self, *args, **kwargs):
46 fields = (forms.DateField(), forms.DateField())
47 super().__init__(fields, *args, **kwargs)
48
49 def compress(self, data_list):
50 if data_list:
51 start_date, stop_date = data_list
52 if start_date:
53 start_date = handle_timezone(
54 datetime.combine(start_date, time.min), False
55 )
56 if stop_date:
57 stop_date = handle_timezone(
58 datetime.combine(stop_date, time.max), False
59 )
60 return slice(start_date, stop_date)
61 return None
62
63
64 class DateTimeRangeField(RangeField):
65 widget = DateRangeWidget
66
67 def __init__(self, *args, **kwargs):
68 fields = (forms.DateTimeField(), forms.DateTimeField())
69 super().__init__(fields, *args, **kwargs)
70
71
72 class IsoDateTimeRangeField(RangeField):
73 widget = DateRangeWidget
74
75 def __init__(self, *args, **kwargs):
76 fields = (IsoDateTimeField(), IsoDateTimeField())
77 super().__init__(fields, *args, **kwargs)
78
79
80 class TimeRangeField(RangeField):
81 widget = DateRangeWidget
82
83 def __init__(self, *args, **kwargs):
84 fields = (forms.TimeField(), forms.TimeField())
85 super().__init__(fields, *args, **kwargs)
86
87
88 class Lookup(namedtuple("Lookup", ("value", "lookup_expr"))):
89 def __new__(cls, value, lookup_expr):
90 if value in EMPTY_VALUES or lookup_expr in EMPTY_VALUES:
91 raise ValueError(
92 "Empty values ([], (), {}, '', None) are not "
93 "valid Lookup arguments. Return None instead."
94 )
95
96 return super().__new__(cls, value, lookup_expr)
97
98
99 class LookupChoiceField(forms.MultiValueField):
100 default_error_messages = {
101 "lookup_required": _("Select a lookup."),
102 }
103
104 def __init__(self, field, lookup_choices, *args, **kwargs):
105 empty_label = kwargs.pop("empty_label", settings.EMPTY_CHOICE_LABEL)
106 fields = (field, ChoiceField(choices=lookup_choices, empty_label=empty_label))
107 widget = LookupChoiceWidget(widgets=[f.widget for f in fields])
108 kwargs["widget"] = widget
109 kwargs["help_text"] = field.help_text
110 super().__init__(fields, *args, **kwargs)
111
112 def compress(self, data_list):
113 if len(data_list) == 2:
114 value, lookup_expr = data_list
115 if value not in EMPTY_VALUES:
116 if lookup_expr not in EMPTY_VALUES:
117 return Lookup(value=value, lookup_expr=lookup_expr)
118 else:
119 raise forms.ValidationError(
120 self.error_messages["lookup_required"], code="lookup_required"
121 )
122 return None
123
124
125 class IsoDateTimeField(forms.DateTimeField):
126 """
127 Supports 'iso-8601' date format too which is out the scope of
128 the ``datetime.strptime`` standard library
129
130 # ISO 8601: ``http://www.w3.org/TR/NOTE-datetime``
131
132 Based on Gist example by David Medina https://gist.github.com/copitux/5773821
133 """
134
135 ISO_8601 = "iso-8601"
136 input_formats = [ISO_8601]
137
138 def strptime(self, value, format):
139 value = force_str(value)
140
141 if format == self.ISO_8601:
142 parsed = parse_datetime(value)
143 if parsed is None: # Continue with other formats if doesn't match
144 raise ValueError
145 return handle_timezone(parsed)
146 return super().strptime(value, format)
147
148
149 class BaseCSVField(forms.Field):
150 """
151 Base field for validating CSV types. Value validation is performed by
152 secondary base classes.
153
154 ex::
155 class IntegerCSVField(BaseCSVField, filters.IntegerField):
156 pass
157
158 """
159
160 base_widget_class = BaseCSVWidget
161
162 def __init__(self, *args, **kwargs):
163 widget = kwargs.get("widget") or self.widget
164 kwargs["widget"] = self._get_widget_class(widget)
165
166 super().__init__(*args, **kwargs)
167
168 def _get_widget_class(self, widget):
169 # passthrough, allows for override
170 if isinstance(widget, BaseCSVWidget) or (
171 isinstance(widget, type) and issubclass(widget, BaseCSVWidget)
172 ):
173 return widget
174
175 # complain since we are unable to reconstruct widget instances
176 assert isinstance(
177 widget, type
178 ), "'%s.widget' must be a widget class, not %s." % (
179 self.__class__.__name__,
180 repr(widget),
181 )
182
183 bases = (
184 self.base_widget_class,
185 widget,
186 )
187 return type(str("CSV%s" % widget.__name__), bases, {})
188
189 def clean(self, value):
190 if value in self.empty_values and self.required:
191 raise forms.ValidationError(
192 self.error_messages["required"], code="required"
193 )
194
195 if value is None:
196 return None
197 return [super(BaseCSVField, self).clean(v) for v in value]
198
199
200 class BaseRangeField(BaseCSVField):
201 # Force use of text input, as range must always have two inputs. A date
202 # input would only allow a user to input one value and would always fail.
203 widget = CSVWidget
204
205 default_error_messages = {"invalid_values": _("Range query expects two values.")}
206
207 def clean(self, value):
208 value = super().clean(value)
209
210 assert value is None or isinstance(value, list)
211
212 if value and len(value) != 2:
213 raise forms.ValidationError(
214 self.error_messages["invalid_values"], code="invalid_values"
215 )
216
217 return value
218
219
220 class ChoiceIterator(BaseChoiceIterator if DJANGO_50 else object):
221 # Emulates the behavior of ModelChoiceIterator, but instead wraps
222 # the field's _choices iterable.
223
224 def __init__(self, field, choices):
225 self.field = field
226 self.choices = choices
227
228 def __iter__(self):
229 if self.field.empty_label is not None:
230 yield ("", self.field.empty_label)
231 if self.field.null_label is not None:
232 yield (self.field.null_value, self.field.null_label)
233 if DJANGO_50:
234 yield from normalize_choices(self.choices)
235 else:
236 yield from self.choices
237
238 def __len__(self):
239 add = 1 if self.field.empty_label is not None else 0
240 add += 1 if self.field.null_label is not None else 0
241 return len(self.choices) + add
242
243
244 class ModelChoiceIterator(forms.models.ModelChoiceIterator):
245 # Extends the base ModelChoiceIterator to add in 'null' choice handling.
246 # This is a bit verbose since we have to insert the null choice after the
247 # empty choice, but before the remainder of the choices.
248
249 def __iter__(self):
250 iterable = super().__iter__()
251
252 if self.field.empty_label is not None:
253 yield next(iterable)
254 if self.field.null_label is not None:
255 yield (self.field.null_value, self.field.null_label)
256 yield from iterable
257
258 def __len__(self):
259 add = 1 if self.field.null_label is not None else 0
260 return super().__len__() + add
261
262
263 class ChoiceIteratorMixin:
264 def __init__(self, *args, **kwargs):
265 self.null_label = kwargs.pop("null_label", settings.NULL_CHOICE_LABEL)
266 self.null_value = kwargs.pop("null_value", settings.NULL_CHOICE_VALUE)
267
268 super().__init__(*args, **kwargs)
269
270 @property
271 def choices(self):
272 return super().choices
273
274 @choices.setter
275 def choices(self, value):
276 if DJANGO_50:
277 value = self.iterator(self, value)
278 # Simple `super()` syntax for calling a parent property setter is
279 # unsupported. See https://github.com/python/cpython/issues/59170
280 super(ChoiceIteratorMixin, self.__class__).choices.__set__(self, value)
281 else:
282 super()._set_choices(value)
283 value = self.iterator(self, self._choices)
284 self._choices = self.widget.choices = value
285
286
287 # Unlike their Model* counterparts, forms.ChoiceField and forms.MultipleChoiceField do not set empty_label
288 class ChoiceField(ChoiceIteratorMixin, forms.ChoiceField):
289 iterator = ChoiceIterator
290
291 def __init__(self, *args, **kwargs):
292 self.empty_label = kwargs.pop("empty_label", settings.EMPTY_CHOICE_LABEL)
293 super().__init__(*args, **kwargs)
294
295
296 class MultipleChoiceField(ChoiceIteratorMixin, forms.MultipleChoiceField):
297 iterator = ChoiceIterator
298
299 def __init__(self, *args, **kwargs):
300 self.empty_label = None
301 super().__init__(*args, **kwargs)
302
303
304 class ModelChoiceField(ChoiceIteratorMixin, forms.ModelChoiceField):
305 iterator = ModelChoiceIterator
306
307 def to_python(self, value):
308 # bypass the queryset value check
309 if self.null_label is not None and value == self.null_value:
310 return value
311 return super().to_python(value)
312
313
314 class ModelMultipleChoiceField(ChoiceIteratorMixin, forms.ModelMultipleChoiceField):
315 iterator = ModelChoiceIterator
316
317 def _check_values(self, value):
318 null = self.null_label is not None and value and self.null_value in value
319 if null: # remove the null value and any potential duplicates
320 value = [v for v in value if v != self.null_value]
321
322 result = list(super()._check_values(value))
323 result += [self.null_value] if null else []
324 return result