Fix to_python not working with non-json values

This commit is contained in:
Swen Kooij 2017-05-25 18:11:58 +03:00
parent cff22855c2
commit 093a9d58f2
2 changed files with 20 additions and 4 deletions

View File

@ -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

View File

@ -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