From 18af18119113ab1f655aa68787aec5f5fd066929 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Thu, 13 Aug 2015 09:56:03 +0100 Subject: [PATCH] Fix boolean checkboxes setting to False. Closes #3258. Closes #2776. --- rest_framework/fields.py | 4 +--- tests/test_fields.py | 24 ++++++++++++++++-------- 2 files changed, 17 insertions(+), 11 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 5a3ea5c8e..9cd5c313f 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -280,9 +280,7 @@ class Field(object): self.allow_null = allow_null if self.default_empty_html is not empty: - if not required: - self.default_empty_html = empty - elif default is not empty: + if default is not empty: self.default_empty_html = default if validators is not None: diff --git a/tests/test_fields.py b/tests/test_fields.py index 455b47ad2..0fea45a33 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -227,19 +227,27 @@ class TestInvalidErrorKey: class TestBooleanHTMLInput: - def setup(self): - class TestSerializer(serializers.Serializer): - archived = serializers.BooleanField() - self.Serializer = TestSerializer - def test_empty_html_checkbox(self): """ HTML checkboxes do not send any value, but should be treated as `False` by BooleanField. """ - # This class mocks up a dictionary like object, that behaves - # as if it was returned for multipart or urlencoded data. - serializer = self.Serializer(data=QueryDict('')) + class TestSerializer(serializers.Serializer): + archived = serializers.BooleanField() + + serializer = TestSerializer(data=QueryDict('')) + assert serializer.is_valid() + assert serializer.validated_data == {'archived': False} + + def test_empty_html_checkbox_not_required(self): + """ + HTML checkboxes do not send any value, but should be treated + as `False` by BooleanField, even if the field is required=False. + """ + class TestSerializer(serializers.Serializer): + archived = serializers.BooleanField(required=False) + + serializer = TestSerializer(data=QueryDict('')) assert serializer.is_valid() assert serializer.validated_data == {'archived': False}