Enhance JSON parsing and normalization in WorkerForm to handle various input types
This commit is contained in:
@@ -168,11 +168,40 @@ class WorkerForm(forms.ModelForm):
|
|||||||
if val is None or val == "":
|
if val is None or val == "":
|
||||||
opts[k] = []
|
opts[k] = []
|
||||||
else:
|
else:
|
||||||
|
# If the cleaned value is a JSON string, parse it. If
|
||||||
|
# it's already a Python structure (possibly containing
|
||||||
|
# pydantic models from `clean()`), keep it but normalize
|
||||||
|
# any model instances into serializable dicts.
|
||||||
|
if isinstance(val, str):
|
||||||
try:
|
try:
|
||||||
parsed = json.loads(val)
|
parsed = json.loads(val)
|
||||||
except Exception:
|
except Exception:
|
||||||
parsed = val
|
parsed = val
|
||||||
opts[k] = parsed
|
else:
|
||||||
|
parsed = val
|
||||||
|
|
||||||
|
def _normalize(obj):
|
||||||
|
# Normalize pydantic BaseModel instances (v2:v1)
|
||||||
|
if hasattr(obj, "model_dump"):
|
||||||
|
try:
|
||||||
|
return obj.model_dump()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
if hasattr(obj, "dict") and not isinstance(obj, dict):
|
||||||
|
try:
|
||||||
|
return obj.dict()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
# Recurse lists/tuples
|
||||||
|
if isinstance(obj, list):
|
||||||
|
return [_normalize(i) for i in obj]
|
||||||
|
if isinstance(obj, tuple):
|
||||||
|
return [_normalize(i) for i in obj]
|
||||||
|
if isinstance(obj, dict):
|
||||||
|
return {k: _normalize(v) for k, v in obj.items()}
|
||||||
|
return obj
|
||||||
|
|
||||||
|
opts[k] = _normalize(parsed)
|
||||||
|
|
||||||
instance.options = opts
|
instance.options = opts
|
||||||
if commit:
|
if commit:
|
||||||
|
|||||||
Reference in New Issue
Block a user