From 8aed3d4862ba1c619a13bb519df55d6e997fccf4 Mon Sep 17 00:00:00 2001 From: Matthew Madurski Date: Sat, 24 Oct 2015 19:44:03 -0400 Subject: [PATCH] Correctly handle false in nested as_form_field --- rest_framework/utils/serializer_helpers.py | 2 +- tests/test_bound_fields.py | 23 ++++++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/rest_framework/utils/serializer_helpers.py b/rest_framework/utils/serializer_helpers.py index ddf160868..b11d3fd07 100644 --- a/rest_framework/utils/serializer_helpers.py +++ b/rest_framework/utils/serializer_helpers.py @@ -112,7 +112,7 @@ class NestedBoundField(BoundField): if isinstance(value, (list, dict)): values[key] = value else: - values[key] = '' if value is None else force_text(value) + values[key] = '' if (value is None or value is False) else force_text(value) return self.__class__(self._field, values, self.errors, self._prefix) diff --git a/tests/test_bound_fields.py b/tests/test_bound_fields.py index bfc54b233..71d49a385 100644 --- a/tests/test_bound_fields.py +++ b/tests/test_bound_fields.py @@ -45,6 +45,16 @@ class TestSimpleBoundField: assert serializer['amount'].errors is None assert serializer['amount'].name == 'amount' + def test_as_form_fields(self): + class ExampleSerializer(serializers.Serializer): + bool_field = serializers.BooleanField() + null_field = serializers.IntegerField(allow_null=True) + + serializer = ExampleSerializer(data={'bool_field': False, 'null_field': None}) + assert serializer.is_valid() + assert serializer['bool_field'].as_form_field().value == '' + assert serializer['null_field'].as_form_field().value == '' + class TestNestedBoundField: def test_nested_empty_bound_field(self): @@ -67,3 +77,16 @@ class TestNestedBoundField: assert serializer['nested']['amount'].value is None assert serializer['nested']['amount'].errors is None assert serializer['nested']['amount'].name == 'nested.amount' + + def test_as_form_fields(self): + class Nested(serializers.Serializer): + bool_field = serializers.BooleanField() + null_field = serializers.IntegerField(allow_null=True) + + class ExampleSerializer(serializers.Serializer): + nested = Nested() + + serializer = ExampleSerializer(data={'nested': {'bool_field': False, 'null_field': None}}) + assert serializer.is_valid() + assert serializer['nested']['bool_field'].as_form_field().value == '' + assert serializer['nested']['null_field'].as_form_field().value == ''