From 2d890be15502a66a27212a3d1d1f11776e6802d3 Mon Sep 17 00:00:00 2001 From: Alexey Sveshnikov Date: Wed, 31 Jan 2024 00:06:39 +0300 Subject: [PATCH] Parse byte values as json as well --- django_pydantic_field/v2/forms.py | 4 ++-- tests/v2/test_forms.py | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/django_pydantic_field/v2/forms.py b/django_pydantic_field/v2/forms.py index 2c69458..510682c 100644 --- a/django_pydantic_field/v2/forms.py +++ b/django_pydantic_field/v2/forms.py @@ -55,11 +55,11 @@ def to_python(self, value: ty.Any) -> ty.Any: return None try: - if not isinstance(value, str): + if not isinstance(value, (str, bytes)): # The form data may contain python objects for some cases (e.g. using django-constance). value = self.adapter.validate_python(value) elif not isinstance(value, JSONString): - # Otherwise, try to parse incoming JSON accoring to the schema. + # Otherwise, try to parse incoming JSON according to the schema. value = self.adapter.validate_json(value) except pydantic.ValidationError as exc: error_params = {"value": value, "title": exc.title, "detail": exc.json(), "errors": exc.errors()} diff --git a/tests/v2/test_forms.py b/tests/v2/test_forms.py index 47f192d..88e9e6a 100644 --- a/tests/v2/test_forms.py +++ b/tests/v2/test_forms.py @@ -21,6 +21,7 @@ class SampleForm(Form): "raw_data, clean_data", [ ('{"stub_str": "abc", "stub_list": ["1970-01-01"]}', {"stub_str": "abc", "stub_list": ["1970-01-01"]}), + (b'{"stub_str": "abc", "stub_list": ["1970-01-01"]}', {"stub_str": "abc", "stub_list": ["1970-01-01"]}), ({"stub_str": "abc", "stub_list": ["1970-01-01"]}, {"stub_str": "abc", "stub_list": ["1970-01-01"]}), (InnerSchema(stub_str="abc", stub_list=[date(1970, 1, 1)]), {"stub_str": "abc", "stub_list": ["1970-01-01"]}), ],