Ticket #11725: django_label_for_none_incl_tests.patch

File django_label_for_none_incl_tests.patch, 2.6 KB (added by DenisMartinez, 14 years ago)

Same patch applied to svn r13303, including tests

  • django/forms/forms.py

     
    481481        id_ = widget.attrs.get('id') or self.auto_id
    482482        if id_:
    483483            attrs = attrs and flatatt(attrs) or ''
    484             contents = u'<label for="%s"%s>%s</label>' % (widget.id_for_label(id_), attrs, unicode(contents))
     484            id_for_label = widget.id_for_label(id_)
     485            if id_for_label:
     486                contents = u'<label for="%s"%s>%s</label>' % (id_for_label, attrs, unicode(contents))
     487            else:
     488                contents = u'<label%s>%s</label>' % (attrs, unicode(contents))
    485489        return mark_safe(contents)
    486490
    487491    def css_classes(self, extra_classes=None):
  • tests/regressiontests/forms/forms.py

     
    10261026<li><label for="id_username">Username:</label> <input id="id_username" type="text" name="username" maxlength="10" /></li>
    10271027<li><label for="id_password">Password:</label> <input type="password" name="password" id="id_password" /></li>
    10281028
     1029A widget can customize the 'for' value of its label by overriding id_for_label.
     1030>>> class UserRegistration(Form):
     1031...    class MyTextInput(TextInput):
     1032...        def id_for_label(self, id):
     1033...            return 'my_' + id
     1034...    username = CharField(max_length=10, widget=MyTextInput)
     1035...    password = CharField(widget=PasswordInput)
     1036>>> p = UserRegistration()
     1037>>> print p.as_ul()
     1038<li><label for="my_id_username">Username:</label> <input id="id_username" type="text" name="username" maxlength="10" /></li>
     1039<li><label for="id_password">Password:</label> <input type="password" name="password" id="id_password" /></li>
    10291040
     1041If id_for_label returns None or is empty, the label won't get a 'for' attribute.
     1042>>> class UserRegistration(Form):
     1043...    class MyTextInput(TextInput):
     1044...        def id_for_label(self, id):
     1045...            return None
     1046...    username = CharField(max_length=10, widget=MyTextInput)
     1047...    password = CharField(widget=PasswordInput)
     1048>>> p = UserRegistration()
     1049>>> print p.as_ul()
     1050<li><label>Username:</label> <input id="id_username" type="text" name="username" maxlength="10" /></li>
     1051<li><label for="id_password">Password:</label> <input type="password" name="password" id="id_password" /></li>
     1052
    10301053# Label Suffix ################################################################
    10311054
    10321055You can specify the 'label_suffix' argument to a Form class to modify the
Back to Top