mirror of
https://github.com/encode/django-rest-framework.git
synced 2024-11-23 01:57:00 +03:00
Merge pull request #2294 from tomchristie/fix-empty-html-values-with-default
Fix empty HTML values when a default is provided.
This commit is contained in:
commit
ad6533e554
|
@ -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()`
|
||||
|
|
|
@ -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[:]
|
||||
|
||||
|
|
|
@ -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')
|
||||
|
|
Loading…
Reference in New Issue
Block a user