diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index e4ef1d4aa..f06db56cf 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -112,6 +112,8 @@ Two options are currently used in HTML form generation, `'input_type'` and `'bas A boolean representation. +When using HTML encoded form input be aware that omitting a value will always be treated as setting a field to `False`, even if it has a `default=True` option specified. This is because HTML checkbox inputs represent the unchecked state by omitting the value, so REST framework treats omission as if it is an empty checkbox input. + Corresponds to `django.db.models.fields.BooleanField`. **Signature:** `BooleanField()` diff --git a/rest_framework/fields.py b/rest_framework/fields.py index f3e17b18d..5be2a21bb 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -185,8 +185,13 @@ class Field(object): self.allow_null = allow_null if allow_null and self.default_empty_html is empty: + # HTML input cannot represent `None` values, so we need to + # forcibly coerce empty HTML values to `None` if `allow_null=True`. self.default_empty_html = None + if default is not empty: + self.default_empty_html = default + if validators is not None: self.validators = validators[:] diff --git a/tests/test_fields.py b/tests/test_fields.py index c20bdd8c2..7f7af5cc0 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -215,6 +215,26 @@ class TestBooleanHTMLInput: assert serializer.validated_data == {'archived': False} +class TestCharHTMLInput: + def setup(self): + class TestSerializer(serializers.Serializer): + message = serializers.CharField(default='happy') + 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. + class MockHTMLDict(dict): + getlist = None + serializer = self.Serializer(data=MockHTMLDict()) + assert serializer.is_valid() + assert serializer.validated_data == {'message': 'happy'} + + class TestCreateOnlyDefault: def setup(self): default = serializers.CreateOnlyDefault('2001-01-01')