2014-03-27 00:44:21 +08:00
|
|
|
import copy
|
2015-12-02 06:59:58 +08:00
|
|
|
from itertools import chain
|
2014-03-27 00:44:21 +08:00
|
|
|
|
|
|
|
from django import forms
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.contrib.postgres.validators import (
|
|
|
|
ArrayMaxLengthValidator, ArrayMinLengthValidator,
|
|
|
|
)
|
|
|
|
from django.core.exceptions import ValidationError
|
2017-01-27 03:58:33 +08:00
|
|
|
from django.utils.translation import gettext_lazy as _
|
2015-12-02 06:59:58 +08:00
|
|
|
|
|
|
|
from ..utils import prefix_validation_error
|
2014-03-27 00:44:21 +08:00
|
|
|
|
|
|
|
|
|
|
|
class SimpleArrayField(forms.CharField):
|
|
|
|
default_error_messages = {
|
2018-05-14 05:57:28 +08:00
|
|
|
'item_invalid': _('Item %(nth)s in the array did not validate:'),
|
2014-03-27 00:44:21 +08:00
|
|
|
}
|
|
|
|
|
2017-06-03 22:49:01 +08:00
|
|
|
def __init__(self, base_field, *, delimiter=',', max_length=None, min_length=None, **kwargs):
|
2014-03-27 00:44:21 +08:00
|
|
|
self.base_field = base_field
|
|
|
|
self.delimiter = delimiter
|
2017-06-03 22:49:01 +08:00
|
|
|
super().__init__(**kwargs)
|
2014-03-27 00:44:21 +08:00
|
|
|
if min_length is not None:
|
|
|
|
self.min_length = min_length
|
|
|
|
self.validators.append(ArrayMinLengthValidator(int(min_length)))
|
|
|
|
if max_length is not None:
|
|
|
|
self.max_length = max_length
|
|
|
|
self.validators.append(ArrayMaxLengthValidator(int(max_length)))
|
|
|
|
|
2017-04-06 22:06:11 +08:00
|
|
|
def clean(self, value):
|
|
|
|
value = super().clean(value)
|
|
|
|
return [self.base_field.clean(val) for val in value]
|
|
|
|
|
2014-03-27 00:44:21 +08:00
|
|
|
def prepare_value(self, value):
|
|
|
|
if isinstance(value, list):
|
2016-12-29 23:27:49 +08:00
|
|
|
return self.delimiter.join(str(self.base_field.prepare_value(v)) for v in value)
|
2014-03-27 00:44:21 +08:00
|
|
|
return value
|
|
|
|
|
|
|
|
def to_python(self, value):
|
2016-11-12 09:07:15 +08:00
|
|
|
if isinstance(value, list):
|
|
|
|
items = value
|
|
|
|
elif value:
|
2014-03-27 00:44:21 +08:00
|
|
|
items = value.split(self.delimiter)
|
|
|
|
else:
|
|
|
|
items = []
|
|
|
|
errors = []
|
|
|
|
values = []
|
2015-12-02 06:59:58 +08:00
|
|
|
for index, item in enumerate(items):
|
2014-03-27 00:44:21 +08:00
|
|
|
try:
|
|
|
|
values.append(self.base_field.to_python(item))
|
2015-12-02 06:59:58 +08:00
|
|
|
except ValidationError as error:
|
|
|
|
errors.append(prefix_validation_error(
|
|
|
|
error,
|
|
|
|
prefix=self.error_messages['item_invalid'],
|
|
|
|
code='item_invalid',
|
2018-04-23 10:18:46 +08:00
|
|
|
params={'nth': index + 1},
|
2015-12-02 06:59:58 +08:00
|
|
|
))
|
2014-03-27 00:44:21 +08:00
|
|
|
if errors:
|
|
|
|
raise ValidationError(errors)
|
|
|
|
return values
|
|
|
|
|
|
|
|
def validate(self, value):
|
2017-01-21 21:13:44 +08:00
|
|
|
super().validate(value)
|
2014-03-27 00:44:21 +08:00
|
|
|
errors = []
|
2015-12-02 06:59:58 +08:00
|
|
|
for index, item in enumerate(value):
|
2014-03-27 00:44:21 +08:00
|
|
|
try:
|
|
|
|
self.base_field.validate(item)
|
2015-12-02 06:59:58 +08:00
|
|
|
except ValidationError as error:
|
|
|
|
errors.append(prefix_validation_error(
|
|
|
|
error,
|
|
|
|
prefix=self.error_messages['item_invalid'],
|
|
|
|
code='item_invalid',
|
2018-04-23 10:18:46 +08:00
|
|
|
params={'nth': index + 1},
|
2015-12-02 06:59:58 +08:00
|
|
|
))
|
2014-03-27 00:44:21 +08:00
|
|
|
if errors:
|
|
|
|
raise ValidationError(errors)
|
|
|
|
|
|
|
|
def run_validators(self, value):
|
2017-01-21 21:13:44 +08:00
|
|
|
super().run_validators(value)
|
2014-03-27 00:44:21 +08:00
|
|
|
errors = []
|
2015-12-02 06:59:58 +08:00
|
|
|
for index, item in enumerate(value):
|
2014-03-27 00:44:21 +08:00
|
|
|
try:
|
|
|
|
self.base_field.run_validators(item)
|
2015-12-02 06:59:58 +08:00
|
|
|
except ValidationError as error:
|
|
|
|
errors.append(prefix_validation_error(
|
|
|
|
error,
|
|
|
|
prefix=self.error_messages['item_invalid'],
|
|
|
|
code='item_invalid',
|
2018-04-23 10:18:46 +08:00
|
|
|
params={'nth': index + 1},
|
2015-12-02 06:59:58 +08:00
|
|
|
))
|
2014-03-27 00:44:21 +08:00
|
|
|
if errors:
|
|
|
|
raise ValidationError(errors)
|
|
|
|
|
2018-01-03 14:40:14 +08:00
|
|
|
def has_changed(self, initial, data):
|
|
|
|
try:
|
|
|
|
value = self.to_python(data)
|
|
|
|
except ValidationError:
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
if initial in self.empty_values and value in self.empty_values:
|
|
|
|
return False
|
|
|
|
return super().has_changed(initial, data)
|
|
|
|
|
2014-03-27 00:44:21 +08:00
|
|
|
|
|
|
|
class SplitArrayWidget(forms.Widget):
|
2017-04-30 07:00:21 +08:00
|
|
|
template_name = 'postgres/widgets/split_array.html'
|
2014-03-27 00:44:21 +08:00
|
|
|
|
|
|
|
def __init__(self, widget, size, **kwargs):
|
|
|
|
self.widget = widget() if isinstance(widget, type) else widget
|
|
|
|
self.size = size
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__(**kwargs)
|
2014-03-27 00:44:21 +08:00
|
|
|
|
|
|
|
@property
|
|
|
|
def is_hidden(self):
|
|
|
|
return self.widget.is_hidden
|
|
|
|
|
|
|
|
def value_from_datadict(self, data, files, name):
|
|
|
|
return [self.widget.value_from_datadict(data, files, '%s_%s' % (name, index))
|
|
|
|
for index in range(self.size)]
|
|
|
|
|
2016-09-07 05:41:54 +08:00
|
|
|
def value_omitted_from_data(self, data, files, name):
|
|
|
|
return all(
|
|
|
|
self.widget.value_omitted_from_data(data, files, '%s_%s' % (name, index))
|
|
|
|
for index in range(self.size)
|
|
|
|
)
|
|
|
|
|
2014-03-27 00:44:21 +08:00
|
|
|
def id_for_label(self, id_):
|
|
|
|
# See the comment for RadioSelect.id_for_label()
|
|
|
|
if id_:
|
|
|
|
id_ += '_0'
|
|
|
|
return id_
|
|
|
|
|
2017-04-30 07:00:21 +08:00
|
|
|
def get_context(self, name, value, attrs=None):
|
|
|
|
attrs = {} if attrs is None else attrs
|
|
|
|
context = super().get_context(name, value, attrs)
|
2014-03-27 00:44:21 +08:00
|
|
|
if self.is_localized:
|
|
|
|
self.widget.is_localized = self.is_localized
|
|
|
|
value = value or []
|
2017-04-30 07:00:21 +08:00
|
|
|
context['widget']['subwidgets'] = []
|
2014-03-27 00:44:21 +08:00
|
|
|
final_attrs = self.build_attrs(attrs)
|
2015-05-14 02:51:18 +08:00
|
|
|
id_ = final_attrs.get('id')
|
2014-03-27 00:44:21 +08:00
|
|
|
for i in range(max(len(value), self.size)):
|
|
|
|
try:
|
|
|
|
widget_value = value[i]
|
|
|
|
except IndexError:
|
|
|
|
widget_value = None
|
|
|
|
if id_:
|
2017-12-11 20:08:45 +08:00
|
|
|
final_attrs = {**final_attrs, 'id': '%s_%s' % (id_, i)}
|
2017-04-30 07:00:21 +08:00
|
|
|
context['widget']['subwidgets'].append(
|
|
|
|
self.widget.get_context(name + '_%s' % i, widget_value, final_attrs)['widget']
|
|
|
|
)
|
|
|
|
return context
|
2014-03-27 00:44:21 +08:00
|
|
|
|
|
|
|
@property
|
|
|
|
def media(self):
|
|
|
|
return self.widget.media
|
|
|
|
|
|
|
|
def __deepcopy__(self, memo):
|
2017-01-21 21:13:44 +08:00
|
|
|
obj = super().__deepcopy__(memo)
|
2014-03-27 00:44:21 +08:00
|
|
|
obj.widget = copy.deepcopy(self.widget)
|
|
|
|
return obj
|
|
|
|
|
|
|
|
@property
|
|
|
|
def needs_multipart_form(self):
|
|
|
|
return self.widget.needs_multipart_form
|
|
|
|
|
|
|
|
|
|
|
|
class SplitArrayField(forms.Field):
|
|
|
|
default_error_messages = {
|
2018-05-14 05:57:28 +08:00
|
|
|
'item_invalid': _('Item %(nth)s in the array did not validate:'),
|
2014-03-27 00:44:21 +08:00
|
|
|
}
|
|
|
|
|
2017-06-03 22:49:01 +08:00
|
|
|
def __init__(self, base_field, size, *, remove_trailing_nulls=False, **kwargs):
|
2014-03-27 00:44:21 +08:00
|
|
|
self.base_field = base_field
|
|
|
|
self.size = size
|
|
|
|
self.remove_trailing_nulls = remove_trailing_nulls
|
|
|
|
widget = SplitArrayWidget(widget=base_field.widget, size=size)
|
|
|
|
kwargs.setdefault('widget', widget)
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__(**kwargs)
|
2014-03-27 00:44:21 +08:00
|
|
|
|
2019-10-25 20:22:34 +08:00
|
|
|
def _remove_trailing_nulls(self, values):
|
|
|
|
index = None
|
|
|
|
if self.remove_trailing_nulls:
|
|
|
|
for i, value in reversed(list(enumerate(values))):
|
|
|
|
if value in self.base_field.empty_values:
|
|
|
|
index = i
|
|
|
|
else:
|
|
|
|
break
|
|
|
|
if index is not None:
|
|
|
|
values = values[:index]
|
|
|
|
return values, index
|
|
|
|
|
2019-07-03 17:32:43 +08:00
|
|
|
def to_python(self, value):
|
|
|
|
value = super().to_python(value)
|
|
|
|
return [self.base_field.to_python(item) for item in value]
|
|
|
|
|
2014-03-27 00:44:21 +08:00
|
|
|
def clean(self, value):
|
|
|
|
cleaned_data = []
|
|
|
|
errors = []
|
|
|
|
if not any(value) and self.required:
|
|
|
|
raise ValidationError(self.error_messages['required'])
|
|
|
|
max_size = max(self.size, len(value))
|
2015-12-02 06:59:58 +08:00
|
|
|
for index in range(max_size):
|
|
|
|
item = value[index]
|
2014-03-27 00:44:21 +08:00
|
|
|
try:
|
|
|
|
cleaned_data.append(self.base_field.clean(item))
|
|
|
|
except ValidationError as error:
|
2015-12-02 06:59:58 +08:00
|
|
|
errors.append(prefix_validation_error(
|
|
|
|
error,
|
|
|
|
self.error_messages['item_invalid'],
|
2014-03-27 00:44:21 +08:00
|
|
|
code='item_invalid',
|
2018-04-23 10:18:46 +08:00
|
|
|
params={'nth': index + 1},
|
2014-03-27 00:44:21 +08:00
|
|
|
))
|
|
|
|
cleaned_data.append(None)
|
2015-12-02 06:59:58 +08:00
|
|
|
else:
|
|
|
|
errors.append(None)
|
2019-10-25 20:22:34 +08:00
|
|
|
cleaned_data, null_index = self._remove_trailing_nulls(cleaned_data)
|
|
|
|
if null_index is not None:
|
|
|
|
errors = errors[:null_index]
|
2014-03-27 00:44:21 +08:00
|
|
|
errors = list(filter(None, errors))
|
|
|
|
if errors:
|
2015-12-02 06:59:58 +08:00
|
|
|
raise ValidationError(list(chain.from_iterable(errors)))
|
2014-03-27 00:44:21 +08:00
|
|
|
return cleaned_data
|
2019-10-25 20:41:34 +08:00
|
|
|
|
|
|
|
def has_changed(self, initial, data):
|
|
|
|
try:
|
|
|
|
data = self.to_python(data)
|
|
|
|
except ValidationError:
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
data, _ = self._remove_trailing_nulls(data)
|
|
|
|
if initial in self.empty_values and data in self.empty_values:
|
|
|
|
return False
|
|
|
|
return super().has_changed(initial, data)
|