|
1 | | -from typing import Any, Dict, Optional |
| 1 | +from typing import Any, Dict, List, Optional, Union |
2 | 2 |
|
3 | | -from django.forms import Widget |
4 | | -from unfold.widgets import PROSE_CLASSES |
| 3 | +from django.core.validators import EMPTY_VALUES |
| 4 | +from django.forms import MultiWidget, Widget |
| 5 | +from django.http import QueryDict |
| 6 | +from django.utils.datastructures import MultiValueDict |
| 7 | +from unfold.widgets import PROSE_CLASSES, UnfoldAdminTextInputWidget |
5 | 8 |
|
6 | 9 | WYSIWYG_CLASSES = [ |
7 | 10 | *PROSE_CLASSES, |
|
22 | 25 | ] |
23 | 26 |
|
24 | 27 |
|
| 28 | +class ArrayWidget(MultiWidget): |
| 29 | + template_name = "unfold/forms/array.html" |
| 30 | + widget_class = UnfoldAdminTextInputWidget |
| 31 | + |
| 32 | + def __init__(self, *args: Any, **kwargs: Any) -> None: |
| 33 | + widgets = [self.widget_class] |
| 34 | + super().__init__(widgets) |
| 35 | + |
| 36 | + def get_context(self, name: str, value: str, attrs: Dict) -> Dict: |
| 37 | + self._resolve_widgets(value) |
| 38 | + context = super().get_context(name, value, attrs) |
| 39 | + template_widget = UnfoldAdminTextInputWidget() |
| 40 | + template_widget.name = name |
| 41 | + |
| 42 | + context.update({"template": template_widget}) |
| 43 | + return context |
| 44 | + |
| 45 | + def value_from_datadict( |
| 46 | + self, data: QueryDict, files: MultiValueDict, name: str |
| 47 | + ) -> List: |
| 48 | + values = [] |
| 49 | + |
| 50 | + for item in data.getlist(name): |
| 51 | + if item not in EMPTY_VALUES: |
| 52 | + values.append(item) |
| 53 | + |
| 54 | + return values |
| 55 | + |
| 56 | + def value_omitted_from_data( |
| 57 | + self, data: QueryDict, files: MultiValueDict, name: str |
| 58 | + ) -> List: |
| 59 | + return data.getlist(name) not in [[""], *EMPTY_VALUES] |
| 60 | + |
| 61 | + def decompress(self, value: Union[str, List]) -> List: |
| 62 | + if isinstance(value, List): |
| 63 | + return value.split(",") |
| 64 | + |
| 65 | + return [] |
| 66 | + |
| 67 | + def _resolve_widgets(self, value: Optional[Union[List, str]]) -> None: |
| 68 | + if value is None: |
| 69 | + value = [] |
| 70 | + |
| 71 | + elif isinstance(value, List): |
| 72 | + self.widgets = [self.widget_class for item in value] |
| 73 | + else: |
| 74 | + self.widgets = [self.widget_class for item in value.split(",")] |
| 75 | + |
| 76 | + self.widgets_names = ["" for i in range(len(self.widgets))] |
| 77 | + self.widgets = [w() if isinstance(w, type) else w for w in self.widgets] |
| 78 | + |
| 79 | + |
25 | 80 | class WysiwygWidget(Widget): |
26 | 81 | template_name = "unfold/forms/wysiwyg.html" |
27 | 82 |
|
|
0 commit comments