Ticket #9336: checkbox_false.diff

File checkbox_false.diff, 1.8 KB (added by bthomas, 7 years ago)

Accept string versions of True and False, with regression tests

  • django/forms/widgets.py

     
    314314        return super(TimeInput, self).render(name, value, attrs)
    315315
    316316class CheckboxInput(Widget):
    317     def __init__(self, attrs=None, check_test=bool):
     317    def __init__(self, attrs=None, check_test=lambda s: s != 'False' and bool(s)):
    318318        super(CheckboxInput, self).__init__(attrs)
    319319        # check_test is a callable that takes a value and returns True
    320320        # if the checkbox should be checked for that value.
     
    328328            result = False
    329329        if result:
    330330            final_attrs['checked'] = 'checked'
    331         if value not in ('', True, False, None):
     331        if value not in ('', True, False, 'True', 'False', None):
    332332            # Only add the 'value' attribute if a value is non-empty.
    333333            final_attrs['value'] = force_unicode(value)
    334334        return mark_safe(u'<input%s />' % flatatt(final_attrs))
  • tests/regressiontests/forms/widgets.py

     
    279279>>> w.render('is_cool', 'foo')
    280280u'<input checked="checked" type="checkbox" name="is_cool" value="foo" />'
    281281
     282A value of 'False' should be rendered unchecked
     283>>> w.render('is_cool', 'False')
     284u'<input type="checkbox" name="is_cool" />'
     285
     286'True' should be rendered without a value attribute
     287>>> w.render('is_cool', 'True')
     288u'<input checked="checked" type="checkbox" name="is_cool" />'
     289
    282290>>> w.render('is_cool', False, attrs={'class': 'pretty'})
    283291u'<input type="checkbox" name="is_cool" class="pretty" />'
    284292
Back to Top