Ticket #2555: checkfield_fix.patch

File checkfield_fix.patch, 2.4 KB (added by Manuel Saelices <msaelices at yaco dot es>, 18 years ago)

Fixed... it uses Javascript but without JS behaviour is good (same behaviour than before patching)

  • django/forms/__init__.py

     
    443443
    444444    def render(self, data):
    445445        checked_html = ''
     446        field_id = self.get_id()
     447        htmldata = data and 'on' or 'off'
    446448        if data or (data is '' and self.checked_by_default):
    447449            checked_html = ' checked="checked"'
    448         return '<input type="checkbox" id="%s" class="v%s" name="%s"%s />' % \
    449             (self.get_id(), self.__class__.__name__,
    450             self.field_name, checked_html)
     450        output = ['''<script>
     451      function toggle_%(id)s_boolean() {
     452        vis = document.getElementById('%(id)s');
     453        hidden = document.getElementById('%(id)s_hidden');
     454        if (vis.checked) { hidden.value = 'on';
     455        } else { hidden.value = 'off';
     456        }
     457        return true;
     458      }
     459      function create_%(id)s_hidden() {
     460        hidden = document.getElementById('dummy_%(id)s_hidden');
     461        hidden.innerHTML = '<input type="hidden" id="%(id)s_hidden" name="%(name)s_hidden" value="%(value)s" />';
     462      }
     463      </script>''' % {'id': field_id, 'name': self.field_name, 'value': escape(htmldata) }]
     464        output.append('<input type="checkbox" id="%s" class="v%s" name="%s" onClick="toggle_%s_boolean(); return true;" %s />' % \
     465            (field_id, self.__class__.__name__,
     466            self.field_name, field_id, checked_html))
     467        output.append('<span id="dummy_%s_hidden"></span>' % field_id)
     468        output.append('<script>create_%s_hidden();</script>' % field_id)
     469        return '\n'.join(output)
    451470
     471    def run_validator(self, new_data, validator):
     472        """ overridden to have the right behaviour with validators when no data is posted """
     473        if new_data.has_key('%s_hidden' % self.field_name) and not new_data.has_key(self.field_name):
     474            # we use internally hidden field with right value
     475            new_data[self.field_name] = new_data.get('%s_hidden' % self.field_name)
     476        super(CheckboxField, self).run_validator(new_data, validator)
     477
    452478    def html2python(data):
    453479        "Convert value from browser ('on' or '') to a Python boolean"
    454480        if data == 'on':
    455481            return True
    456         return False
     482        return False # if not set or set to 'off'
    457483    html2python = staticmethod(html2python)
    458484
    459485class SelectField(FormField):
Back to Top