Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Fix empty HTML values when a default is provided.
  • Loading branch information
lovelydinosaur committed Dec 17, 2014
commit 3fff5cb6e0960b7ff8abd9f13a075f1f057de0a7
2 changes: 2 additions & 0 deletions docs/api-guide/fields.md
Original file line number Diff line number Diff line change
Expand Up @@ -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()`
Expand Down
5 changes: 5 additions & 0 deletions rest_framework/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,8 +185,13 @@ def __init__(self, read_only=False, write_only=False,
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[:]

Expand Down
20 changes: 20 additions & 0 deletions tests/test_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,26 @@ class MockHTMLDict(dict):
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')
Expand Down