Skip to content

Commit

Permalink
Fixed #16820 -- Treated '0' value as True for checkbox inputs
Browse files Browse the repository at this point in the history
Thanks Dan Fairs for the report and the initial patch.
  • Loading branch information
claudep committed Oct 26, 2012
1 parent 90c7656 commit be29329
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 1 deletion.
2 changes: 1 addition & 1 deletion django/forms/widgets.py
Expand Up @@ -528,7 +528,7 @@ def value_from_datadict(self, data, files, name):
values = {'true': True, 'false': False}
if isinstance(value, six.string_types):
value = values.get(value.lower(), value)
return value
return bool(value)

def _has_changed(self, initial, data):
# Sometimes data or initial could be None or '' which should be the
Expand Down
5 changes: 5 additions & 0 deletions tests/regressiontests/forms/tests/forms.py
Expand Up @@ -269,6 +269,11 @@ class SignupForm(Form):
f = SignupForm({'email': 'test@example.com', 'get_spam': 'false'}, auto_id=False)
self.assertHTMLEqual(str(f['get_spam']), '<input type="checkbox" name="get_spam" />')

# A value of '0' should be interpreted as a True value (#16820)
f = SignupForm({'email': 'test@example.com', 'get_spam': '0'})
self.assertTrue(f.is_valid())
self.assertTrue(f.cleaned_data.get('get_spam'))

def test_widget_output(self):
# Any Field can have a Widget class passed to its constructor:
class ContactForm(Form):
Expand Down
4 changes: 4 additions & 0 deletions tests/regressiontests/forms/tests/widgets.py
Expand Up @@ -225,6 +225,10 @@ def test_checkboxinput(self):
# checkboxes).
self.assertFalse(w.value_from_datadict({}, {}, 'testing'))

value = w.value_from_datadict({'testing': '0'}, {}, 'testing')
self.assertIsInstance(value, bool)
self.assertTrue(value)

self.assertFalse(w._has_changed(None, None))
self.assertFalse(w._has_changed(None, ''))
self.assertFalse(w._has_changed('', None))
Expand Down

0 comments on commit be29329

Please sign in to comment.