schon/core/widgets.py
Egor fureunoir Gorbunov fdd92dbf8b Features: 1) Introduced strict parameter for zip function in widgets.py; 2) Added EXTENSIONS_MAX_UNIQUE_QUERY_ATTEMPTS setting;
Fixes: 1) Resolved redundant lines and formatting inconsistencies across multiple files; 2) Corrected Collection typing imports and Optional replacements with union types (e.g., `str | None`);

Extra: Improved formatting and readability by consolidating single-line code sections and simplifying expressions.
2025-06-21 20:38:37 +03:00

39 lines
1.2 KiB
Python

import json
from django import forms
class JSONTableWidget(forms.Widget):
template_name = "json_table_widget.html"
def format_value(self, value):
if isinstance(value, dict):
return value
try:
if isinstance(value, str):
value = json.loads(value)
except json.JSONDecodeError:
value = {}
return value
def render(self, name, value, attrs=None, renderer=None):
value = self.format_value(value)
return super().render(name, value, attrs, renderer)
# noinspection PyUnresolvedReferences
def value_from_datadict(self, data, files, name):
json_data = {}
try:
keys = data.getlist(f"{name}_key")
values = data.getlist(f"{name}_value")
for key, value in zip(keys, values, strict=True):
if key.strip():
try:
json_data[key] = json.loads(value)
except (json.JSONDecodeError, ValueError):
json_data[key] = value
except TypeError:
pass
return None if not json_data else json.dumps(json_data)