Fix default values always being False for browsable API

This fixes a bug that was introduced in 28ff6fb [1] for the
browsable API, specifically with how it handled default values
for boolean fields.  Previously, it had a global default for
boolean fields set to `False`, which was different than the
standard None that was used elsewhere.  Because this only needed
to be done for the browsable API, a fix was put into place that
only set the default to `False` when form data was passed into
the serializer.  This had the unintended side effect of overriding
any default set on the boolean field.

This fixes #1101 [2] by only overriding the default if the default is
`None`, which is the default for all fields.

[1]: 28ff6fb1ec
[2]: https://github.com/tomchristie/django-rest-framework/issues/1101
This commit is contained in:
Kevin Brown 2013-12-13 12:41:44 -05:00
parent ca244ad614
commit 90edcbf938
2 changed files with 40 additions and 1 deletions

View File

@ -428,7 +428,7 @@ class BooleanField(WritableField):
def field_from_native(self, data, files, field_name, into):
# HTML checkboxes do not explicitly represent unchecked as `False`
# we deal with that here...
if isinstance(data, QueryDict):
if isinstance(data, QueryDict) and self.default is None:
self.default = False
return super(BooleanField, self).field_from_native(

View File

@ -1743,3 +1743,42 @@ class TestSerializerTransformMethods(TestCase):
'b_renamed': None,
}
)
class DefaultTrueBooleanModel(models.Model):
cat = models.BooleanField(default=True)
dog = models.BooleanField(default=False)
class SerializerDefaultTrueBoolean(TestCase):
def setUp(self):
super(SerializerDefaultTrueBoolean, self).setUp()
class DefaultTrueBooleanSerializer(serializers.ModelSerializer):
class Meta:
model = DefaultTrueBooleanModel
fields = ('cat', 'dog')
self.default_true_boolean_serializer = DefaultTrueBooleanSerializer
def test_enabled_as_false(self):
serializer = self.default_true_boolean_serializer(data={'cat': False,
'dog': False})
self.assertEqual(serializer.is_valid(), True)
self.assertEqual(serializer.data['cat'], False)
self.assertEqual(serializer.data['dog'], False)
def test_enabled_as_true(self):
serializer = self.default_true_boolean_serializer(data={'cat': True,
'dog': True})
self.assertEqual(serializer.is_valid(), True)
self.assertEqual(serializer.data['cat'], True)
self.assertEqual(serializer.data['dog'], True)
def test_enabled_partial(self):
serializer = self.default_true_boolean_serializer(data={'cat': False},
partial=True)
self.assertEqual(serializer.is_valid(), True)
self.assertEqual(serializer.data['cat'], False)
self.assertEqual(serializer.data['dog'], False)