From 093a9d58f2063ec9b683a3f50ddef2d32e70b306 Mon Sep 17 00:00:00 2001 From: Swen Kooij Date: Thu, 25 May 2017 18:11:58 +0300 Subject: [PATCH] Fix to_python not working with non-json values --- localized_fields/fields/localized_field.py | 16 ++++++++++++---- tests/test_localized_field.py | 8 ++++++++ 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/localized_fields/fields/localized_field.py b/localized_fields/fields/localized_field.py index 8798892..d90e23d 100644 --- a/localized_fields/fields/localized_field.py +++ b/localized_fields/fields/localized_field.py @@ -1,3 +1,5 @@ +import json + from typing import Union from django.conf import settings @@ -129,12 +131,18 @@ class LocalizedField(HStoreField): A :see:LocalizedValue instance containing the data extracted from the database. """ - # make deserialization if need by parent method - value = super(LocalizedField, self).to_python(value) - if not value or not isinstance(value, dict): + + # first let the base class handle the deserialization, this is in case we + # get specified a json string representing a dict + try: + deserialized_value = super(LocalizedField, self).to_python(value) + except json.JSONDecodeError: + deserialized_value = value + + if not deserialized_value: return self.attr_class() - return self.attr_class(value) + return self.attr_class(deserialized_value) def get_prep_value(self, value: LocalizedValue) -> dict: """Turns the specified value into something the database diff --git a/tests/test_localized_field.py b/tests/test_localized_field.py index 7495770..9d625ec 100644 --- a/tests/test_localized_field.py +++ b/tests/test_localized_field.py @@ -209,6 +209,14 @@ class LocalizedFieldTestCase(TestCase): for language, value in input_data.items(): assert localized_value.get(language) == value + @staticmethod + def test_to_python_non_json(): + """Tests whether the :see:to_python function + properly handles a string that is not JSON.""" + + localized_value = LocalizedField().to_python('my value') + assert localized_value.get() == 'my value' + @staticmethod def test_to_python_none(): """Tests whether the :see:to_python function