Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions rest_framework/utils/serializer_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,10 +86,13 @@ def as_form_field(self):
class JSONBoundField(BoundField):
def as_form_field(self):
value = self.value
try:
value = json.dumps(self.value, sort_keys=True, indent=4)
except (TypeError, ValueError):
pass
# When HTML form input is used and the input is not valid
# value will be a JSONString, rather than a JSON primitive.
if not getattr(value, 'is_json_string', False):
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)


Expand Down
14 changes: 14 additions & 0 deletions tests/test_bound_fields.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from django.http import QueryDict

from rest_framework import serializers


Expand Down Expand Up @@ -160,3 +162,15 @@ class ExampleSerializer(serializers.Serializer):
)
rendered_packed = ''.join(rendered.split())
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"}'