Stop JSONBoundField mangling invalid JSON (#5526) (#5527)

This commit is contained in:
Jamie Cockburn 2017-10-25 09:54:38 +01:00 committed by Carlton Gibson
parent 1c9ad52cb6
commit 91fa8b923a
2 changed files with 21 additions and 4 deletions

View File

@ -86,10 +86,13 @@ class BoundField(object):
class JSONBoundField(BoundField): class JSONBoundField(BoundField):
def as_form_field(self): def as_form_field(self):
value = self.value value = self.value
try: # When HTML form input is used and the input is not valid
value = json.dumps(self.value, sort_keys=True, indent=4) # value will be a JSONString, rather than a JSON primitive.
except (TypeError, ValueError): if not getattr(value, 'is_json_string', False):
pass try:
value = json.dumps(self.value, sort_keys=True, indent=4)
except (TypeError, ValueError):
pass
return self.__class__(self._field, value, self.errors, self._prefix) return self.__class__(self._field, value, self.errors, self._prefix)

View File

@ -1,3 +1,5 @@
from django.http import QueryDict
from rest_framework import serializers from rest_framework import serializers
@ -160,3 +162,15 @@ class TestNestedBoundField:
) )
rendered_packed = ''.join(rendered.split()) rendered_packed = ''.join(rendered.split())
assert rendered_packed == expected_packed assert rendered_packed == expected_packed
class TestJSONBoundField:
def test_as_form_fields(self):
class TestSerializer(serializers.Serializer):
json_field = serializers.JSONField()
data = QueryDict(mutable=True)
data.update({'json_field': '{"some": ["json"}'})
serializer = TestSerializer(data=data)
assert serializer.is_valid() is False
assert serializer['json_field'].as_form_field().value == '{"some": ["json"}'