Handle non-dict values for NestedSerializer during BrowsableAPI
rendering.
This commit is contained in:
Berkant 2021-03-09 14:34:18 +03:00 committed by GitHub
parent 05512160ab
commit 95ae92ef23
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 29 additions and 2 deletions

View File

@ -1,5 +1,5 @@
from collections import OrderedDict from collections import OrderedDict
from collections.abc import MutableMapping from collections.abc import Mapping, MutableMapping
from django.utils.encoding import force_str from django.utils.encoding import force_str
@ -101,7 +101,7 @@ class NestedBoundField(BoundField):
""" """
def __init__(self, field, value, errors, prefix=''): def __init__(self, field, value, errors, prefix=''):
if value is None or value == '': if value is None or value == '' or not isinstance(value, Mapping):
value = {} value = {}
super().__init__(field, value, errors, prefix) super().__init__(field, value, errors, prefix)

View File

@ -163,6 +163,33 @@ class TestNestedBoundField:
rendered_packed = ''.join(rendered.split()) rendered_packed = ''.join(rendered.split())
assert rendered_packed == expected_packed assert rendered_packed == expected_packed
def test_rendering_nested_fields_with_not_mappable_value(self):
from rest_framework.renderers import HTMLFormRenderer
class Nested(serializers.Serializer):
text_field = serializers.CharField()
class ExampleSerializer(serializers.Serializer):
nested = Nested()
serializer = ExampleSerializer(data={'nested': 1})
assert not serializer.is_valid()
renderer = HTMLFormRenderer()
for field in serializer:
rendered = renderer.render_field(field, {})
expected_packed = (
'<fieldset>'
'<legend>Nested</legend>'
'<divclass="form-group">'
'<label>Textfield</label>'
'<inputname="nested.text_field"class="form-control"type="text"value="">'
'</div>'
'</fieldset>'
)
rendered_packed = ''.join(rendered.split())
assert rendered_packed == expected_packed
class TestJSONBoundField: class TestJSONBoundField:
def test_as_form_fields(self): def test_as_form_fields(self):