2021-05-10 20:13:42 +00:00
|
|
|
from django.core import validators
|
2021-10-16 17:43:20 +00:00
|
|
|
from django.core.exceptions import ValidationError
|
|
|
|
|
from django.forms.widgets import Textarea
|
2021-05-10 20:13:42 +00:00
|
|
|
|
2024-09-01 15:21:47 +00:00
|
|
|
EMPTY_VALUES = (*validators.EMPTY_VALUES, "[]")
|
2021-10-16 17:43:02 +00:00
|
|
|
|
2021-05-10 20:13:42 +00:00
|
|
|
|
|
|
|
|
class CSVWidget(Textarea):
|
|
|
|
|
is_hidden = False
|
|
|
|
|
|
|
|
|
|
def prep_value(self, value):
|
2021-10-16 17:43:02 +00:00
|
|
|
"""Prepare value before effectively render widget"""
|
2021-05-10 20:13:42 +00:00
|
|
|
if value in EMPTY_VALUES:
|
|
|
|
|
return ""
|
2024-09-01 15:21:47 +00:00
|
|
|
if isinstance(value, str):
|
2021-05-10 20:13:42 +00:00
|
|
|
return value
|
2024-09-01 15:21:47 +00:00
|
|
|
if isinstance(value, list):
|
2021-05-10 20:13:42 +00:00
|
|
|
return ";".join(value)
|
2024-09-01 15:21:47 +00:00
|
|
|
raise ValidationError("Invalid format.")
|
2021-05-10 20:13:42 +00:00
|
|
|
|
|
|
|
|
def render(self, name, value, **kwargs):
|
|
|
|
|
value = self.prep_value(value)
|
|
|
|
|
return super().render(name, value, **kwargs)
|
2022-06-13 04:58:44 +00:00
|
|
|
|
|
|
|
|
def value_from_datadict(self, data, files, name):
|
|
|
|
|
"""
|
|
|
|
|
Return the value of this widget or None.
|
|
|
|
|
|
|
|
|
|
Since we're only given the value of the entity name and the data dict
|
|
|
|
|
contains the '_eav_config_cls' (which we don't have access to) as the
|
|
|
|
|
key, we need to loop through each field checking if the eav attribute
|
|
|
|
|
exists with the given 'name'.
|
|
|
|
|
"""
|
2024-09-01 15:21:47 +00:00
|
|
|
for data_value in data.values():
|
|
|
|
|
widget_value = getattr(data_value, name, None)
|
|
|
|
|
if widget_value is not None:
|
|
|
|
|
return widget_value
|
|
|
|
|
|
|
|
|
|
return None
|