Django使用CheckboxSelectMultiple小部件</ul>设置<ul>的类而不是<input />

时间:2011-10-21 16:46:17

标签: django django-forms

我可以使用类似

的行设置窗口小部件的类
self.widget = forms.CheckboxSelectMultiple(attrs={'class': 'myclass'})

但这会将myclass应用于所有<li>元素,例如

<ul>
    <label><li><input type="checkbox" class="myclass">1</li></label>
    <label><li><input type="checkbox" class="myclass">2</li></label>
    <label><li><input type="checkbox" class="myclass">3</li></label>
</ul>

如何将课程仅应用于<ul>元素?

2 个答案:

答案 0 :(得分:4)

默认情况下,您无法在UL标记上设置该属性。 “简单”的事情是将CheckboxSelectMultiple子类化为您想要的。有两种方法:

使用“ulattrs”参数构造CheckboxSelectMultiple的自定义版本。

class MyCheckboxSelectMultiple(CheckboxSelectMultiple):
    def render(self, name, value, ulattrs=None, attrs=None, choices=()):
        if value is None: value = []
        has_id = attrs and 'id' in attrs
        final_attrs = self.build_attrs(attrs, name=name)
        output = [u'<ul class="%s">' % ulattrs.get('class')]
        # Normalize to strings
        str_values = set([force_unicode(v) for v in value])
        for i, (option_value, option_label) in enumerate(chain(self.choices, choices)):
            # If an ID attribute was given, add a numeric index as a suffix,
            # so that the checkboxes don't all have the same ID attribute.
            if has_id:
                final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i))
                label_for = u' for="%s"' % final_attrs['id']
            else:
                label_for = ''

            cb = CheckboxInput(final_attrs, check_test=lambda value: value in str_values)
            option_value = force_unicode(option_value)
            rendered_cb = cb.render(name, option_value)
            option_label = conditional_escape(force_unicode(option_label))
            output.append(u'<li><label%s>%s %s</label></li>' % (label_for, rendered_cb, option_label))
        output.append(u'</ul>')
        return mark_safe(u'\n'.join(output))

或者,你可以做一些更多的hacky ......

class MyCheckboxSelectMultiple(CheckboxSelectMultiple):
    def render(self, name, value, attrs=None, choices=()):
        html = super(MyCheckboxSelectMultiple, self).render(name, value, attrs, choices)

        return mark_safe(html.replace('<ul>', '<ul class="foobar">'))

答案 1 :(得分:0)

在Koblas的基础上,另一种更通用的方法是:

class CheckboxSelectMultipleULAttrs(forms.CheckboxSelectMultiple):
    """
    Class to allow setting attributes on containing ul in a CheckboxSelectMultiple
    """
    def __init__(self, ulattrs=None, attrs=None, choices=()):
        self.ulattrs = ulattrs
        super(CheckboxSelectMultipleULAttrs, self).__init__(attrs, choices)
        return

    def render(self, name, value, attrs=None, choices=()):
        html = super(CheckboxSelectMultipleULAttrs, self).render(name, value, attrs, choices)
        if not self.ulattrs:
            return html
        return mark_safe(html.replace('<ul>', '<ul ' + self.ulattrs + '>'))