Merge pull request 'Improve instance form errors' (#173) from 164-keep-values-on-error into main
All checks were successful
Build and Deploy Staging / build (push) Successful in 52s
Tests / test (push) Successful in 25s
Build and Deploy Staging / deploy (push) Successful in 8s

Reviewed-on: #173
This commit is contained in:
Tobias Brunner 2025-09-12 07:21:29 +00:00
commit 9283c38eaa
4 changed files with 51 additions and 28 deletions

View file

@ -48,18 +48,31 @@ class DynamicArrayWidget(forms.Widget):
def value_from_datadict(self, data, files, name): def value_from_datadict(self, data, files, name):
value = data.get(name) value = data.get(name)
if value: if value is None:
return []
if value == "":
return []
if isinstance(value, list):
return [item for item in value if item is not None and str(item).strip()]
if isinstance(value, str):
if value.strip() == "" or value.strip().lower() == "null":
return []
try: try:
parsed = json.loads(value) parsed = json.loads(value)
if parsed: if parsed is None:
return []
if isinstance(parsed, list):
return [ return [
item item
for item in parsed for item in parsed
if item is not None and str(item).strip() if item is not None and str(item).strip()
] ]
return [] return [parsed] if str(parsed).strip() else []
except (json.JSONDecodeError, TypeError): except (json.JSONDecodeError, TypeError):
pass return [value] if value.strip() else []
return [] return []
@ -104,11 +117,17 @@ class DynamicArrayField(forms.JSONField):
if value is None: if value is None:
return [] return []
if isinstance(value, list): if isinstance(value, list):
return value return [item for item in value if item is not None]
if isinstance(value, str): if isinstance(value, str):
if value.strip() == "" or value.strip().lower() == "null":
return []
try: try:
parsed = json.loads(value) parsed = json.loads(value)
return parsed if isinstance(parsed, list) else [parsed] if parsed is None:
return []
if isinstance(parsed, list):
return [item for item in parsed if item is not None]
return [parsed]
except (json.JSONDecodeError, TypeError): except (json.JSONDecodeError, TypeError):
return [value] if value else [] return [value] if value else []
return [str(value)] return [str(value)]
@ -117,16 +136,24 @@ class DynamicArrayField(forms.JSONField):
"""Handle bound data properly to avoid JSON parsing issues""" """Handle bound data properly to avoid JSON parsing issues"""
if data is None: if data is None:
return initial return initial
# If data is already a list (from our widget), return it as-is
if isinstance(data, list): if isinstance(data, list):
return data return [item for item in data if item is not None and str(item).strip()]
# If data is a string, try to parse it as JSON
if isinstance(data, str): if isinstance(data, str):
if data.strip() == "" or data.strip().lower() == "null":
return []
try: try:
parsed = json.loads(data) parsed = json.loads(data)
return parsed if isinstance(parsed, list) else [parsed] if parsed is None:
return []
if isinstance(parsed, list):
return [
item
for item in parsed
if item is not None and str(item).strip()
]
return [parsed] if str(parsed).strip() else []
except (json.JSONDecodeError, TypeError): except (json.JSONDecodeError, TypeError):
return [data] if data else [] return [data] if data and data.strip() else []
return data return data
def validate(self, value): def validate(self, value):

View file

@ -4,6 +4,7 @@
method="post" method="post"
{% if form_action %}action="{{ form_action }}"{% endif %}> {% if form_action %}action="{{ form_action }}"{% endif %}>
{% csrf_token %} {% csrf_token %}
{% include "frontend/forms/errors.html" %}
<ul class="nav nav-tabs" id="myTab" role="tablist"> <ul class="nav nav-tabs" id="myTab" role="tablist">
{% for fieldset in form.get_fieldsets %} {% for fieldset in form.get_fieldsets %}
{% if not fieldset.hidden %} {% if not fieldset.hidden %}

View file

@ -163,14 +163,12 @@ class ServiceOfferingDetailView(OrganizationViewMixin, HtmxViewMixin, DetailView
) )
return redirect(service_instance.urls.base) return redirect(service_instance.urls.base)
except ValidationError as e: except ValidationError as e:
messages.error(self.request, e.message or str(e)) form.add_error(None, e.message or str(e))
except Exception as e: except Exception as e:
messages.error( error_message = self.organization.add_support_message(
self.request, _(f"Error creating instance: {str(e)}.")
self.organization.add_support_message(
_(f"Error creating instance: {str(e)}.")
),
) )
form.add_error(None, error_message)
# If the form is not valid or if the service creation failed, we render it again # If the form is not valid or if the service creation failed, we render it again
context["service_form"] = form context["service_form"] = form
@ -346,10 +344,6 @@ class ServiceInstanceUpdateView(
kwargs["instance"] = self.object.spec_object kwargs["instance"] = self.object.spec_object
return kwargs return kwargs
def form_invalid(self, form):
messages.error(self.request, form.errors)
return super().form_invalid(form)
def form_valid(self, form): def form_valid(self, form):
try: try:
spec_data = form.get_nested_data().get("spec") spec_data = form.get_nested_data().get("spec")
@ -362,15 +356,13 @@ class ServiceInstanceUpdateView(
) )
return redirect(self.object.urls.base) return redirect(self.object.urls.base)
except ValidationError as e: except ValidationError as e:
messages.error(self.request, e.message or str(e)) form.add_error(None, e.message or str(e))
return self.form_invalid(form) return self.form_invalid(form)
except Exception as e: except Exception as e:
messages.error( error_message = self.organization.add_support_message(
self.request, _(f"Error updating instance: {str(e)}.")
self.organization.add_support_message(
_(f"Error updating instance: {str(e)}.")
),
) )
form.add_error(None, error_message)
return self.form_invalid(form) return self.form_invalid(form)
def get_success_url(self): def get_success_url(self):

View file

@ -19,6 +19,9 @@ const initDynamicArrayWidget = () => {
addRemoveEventListeners(container) addRemoveEventListeners(container)
addInputEventListeners(container) addInputEventListeners(container)
updateRemoveButtonVisibility(container) updateRemoveButtonVisibility(container)
// Ensure hidden input is synced with visible inputs on initialization
updateHiddenInput(container)
}) })
} }
@ -94,7 +97,7 @@ const updateHiddenInput = (container) => {
if (!hiddenInput) return if (!hiddenInput) return
const values = Array.from(inputs) const values = Array.from(inputs)
.map(input => input.value.trim()) .map(input => input.value ? input.value.trim() : '')
.filter(value => value !== '') .filter(value => value !== '')
hiddenInput.value = JSON.stringify(values) hiddenInput.value = JSON.stringify(values)