From 61b6244ec65705c7a647194ac4f7f3d610855dba Mon Sep 17 00:00:00 2001 From: rodrperezi Date: Thu, 11 Mar 2021 11:57:10 -0300 Subject: [PATCH] fix(empty form field): allows empty form field when submit through admin - when editting a model with NDArrayField blank or null True through the admin panel, the form sends an empty str which was marked as invalid. - Now field validation allows handling that case by treating value as None --- ndarraydjango/fields.py | 12 ++++++++++++ ndarraydjango/forms.py | 2 ++ 2 files changed, 14 insertions(+) diff --git a/ndarraydjango/fields.py b/ndarraydjango/fields.py index 497c9a6..3c8e49d 100644 --- a/ndarraydjango/fields.py +++ b/ndarraydjango/fields.py @@ -80,6 +80,13 @@ def from_db_value(self, value, expression, connection): return parse_numpy_array(value) def validate(self, value, model_instance): + + if ( + ( value is None and self.blank ) or + ( value is None and self.null ) + ): + return + if self.shape is not None and value.shape != self.shape: raise exceptions.ValidationError("Bad shape", code="shape") @@ -103,6 +110,11 @@ def to_python(self, value): return value if isinstance(value, str): + if ( + ( value=='' and self.blank ) or + ( value=='' and self.null ) + ): + return None try: value = np.array(json.loads(value), dtype=self.dtype) except json.decoder.JSONDecodeError: diff --git a/ndarraydjango/forms.py b/ndarraydjango/forms.py index 1b42156..94a3b8e 100644 --- a/ndarraydjango/forms.py +++ b/ndarraydjango/forms.py @@ -30,6 +30,8 @@ def prepare_value(self, value): def to_python(self, value): value = super().to_python(value) + if (value==self.empty_value) and (not self.required): + return value try: value = json.loads(value) except json.decoder.JSONDecodeError: