From 9ff54c45e09015606754a7fcce824bc78aae9201 Mon Sep 17 00:00:00 2001 From: Étienne Loks Date: Fri, 11 Apr 2025 13:29:15 +0200 Subject: 🐛 document form: fix json fields management MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ishtar_common/forms.py | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) (limited to 'ishtar_common/forms.py') diff --git a/ishtar_common/forms.py b/ishtar_common/forms.py index 07d1ac417..1416dd464 100644 --- a/ishtar_common/forms.py +++ b/ishtar_common/forms.py @@ -308,9 +308,21 @@ class CustomForm(BSForm): c_field.order_number = idx fields[key] = c_field # custom field after classic fields + instance = getattr(self, "instance", None) for k in sorted(new_fields.keys()): alt_key, alt_field = new_fields.pop(k) alt_field.order_number = k + # manage initial data + if instance: + data = instance.data + nok = False + for k_part in alt_key[len("data__"):].split("__"): + if k_part not in data: + nok = True + break + data = data[k_part] + if not nok: + alt_field.initial = data fields[alt_key] = alt_field self.fields = fields self._post_init() @@ -464,6 +476,22 @@ class CustomForm(BSForm): customs.append((key, field.label)) return sorted(customs, key=lambda x: x[1]) + def save_json_fields(self, item): + """ + Edit JSON fields of an item after form validation. + Do not save. Return if item has been changed. + """ + changed = False + for key in self.cleaned_data: + if not key.startswith("data__"): + continue + item.data = update_data( + item.data, + generate_dict_from_data_string(key, self.cleaned_data[key]) + ) + changed = True + return changed + class CustomFormSearch(FormPermissionForm, forms.Form): """ -- cgit v1.2.3