Fix empty HTML values when a default is provided.

This commit is contained in:
Tom Christie 2014-12-17 15:13:48 +00:00
parent 426547c61c
commit 3fff5cb6e0
3 changed files with 27 additions and 0 deletions

View File

@ -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()`

View File

@ -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[:]

View File

@ -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')