gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 02:29:47 25 4
gpt4 key购买 nike

我可以使用类似这样的行设置小部件的类

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>元素?

最佳答案

默认情况下,您无法在 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))

或者,你可以做一些更古怪的事情......

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">'))

关于Django 使用 CheckboxSelectMultiple 小部件设置 <ul> 类而不是 &lt;input&gt;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7852609/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com