allow a non-required nested serializer to validate correctly when receiving multipart data

This commit is contained in:
Juan Gutierrez 2015-07-03 12:28:48 -04:00
parent c091addb83
commit b0c5f9db2f
2 changed files with 44 additions and 1 deletions

View File

@ -367,7 +367,7 @@ class Serializer(BaseSerializer):
# We override the default field access in order to support
# nested HTML forms.
if html.is_html_input(dictionary):
return html.parse_html_dict(dictionary, prefix=self.field_name)
return html.parse_html_dict(dictionary, prefix=self.field_name) or empty
return dictionary.get(self.field_name, empty)
def run_validation(self, data=empty):

View File

@ -38,3 +38,46 @@ class TestNestedSerializer:
}
serializer = self.Serializer()
assert serializer.data == expected_data
class TestNotRequiredNestedSerializer:
def setup(self):
class NestedSerializer(serializers.Serializer):
one = serializers.IntegerField(max_value=10)
class TestSerializer(serializers.Serializer):
nested = NestedSerializer(required=False)
self.Serializer = TestSerializer
class FakeMultiDict(dict):
"""
Use this to fake a `format="multipart"` request, because
`utils.is_html_input()` returns `True` when the dict object has
an attribute of "getlist".
"""
def getlist(self, value, default=None):
if value in self:
return [self[value]]
else:
return [] if default is None else default
self.FakeMultiDict = FakeMultiDict
def test_json_validate(self):
input_data = {}
serializer = self.Serializer(data=input_data)
assert serializer.is_valid()
input_data = {'nested': {'one': '1'}}
serializer = self.Serializer(data=input_data)
assert serializer.is_valid()
def test_multipart_validate(self):
input_data = self.FakeMultiDict()
serializer = self.Serializer(data=input_data)
assert serializer.is_valid()
input_data = self.FakeMultiDict(**{'nested.one': '1'})
serializer = self.Serializer(data=input_data)
assert serializer.is_valid()