Django模型多选字段和小部件checkboxselectmultiple

4

我希望能够拥有类似管理界面的功能。

这里是表单的代码:

class NewRoleFrom(forms.Form):
    role = forms.ModelMultipleChoiceField(
        queryset=Role.objects.all(),
        widget=forms.CheckboxSelectMultiple
    )

所以,很简单,我有一个角色标签(Role:),然后数据库中的每个角色都用复选框呈现。这样,我就可以获取用户选择的所有角色对象。 但是,在每行的开头,我有一个符号,如何去掉它? 然后,是否可以像在admin.py中定义list_display一样,在其他属性上添加?

3个回答

2
在您的表单模板中,只需迭代角色即可。

form.html

{% for role in form.role %}
    <div class="checkbox">
      {{ role }}
    </div>
{% endfor %}

然后使用CSS进行美化。

0
我会用自定义类覆盖CheckboxSelectMultiple类,并直接在渲染输出上插入样式更改。请参见下面的代码。
class CustomCheckboxSelectMultiple(forms.CheckboxSelectMultiple):
    def __init__(self, attrs=None):
        super(CustomCheckboxSelectMultiple, self).__init__(attrs)

    def render(self, name, value, attrs=None, choices=()):
        output = super(CustomCheckboxSelectMultiple, self).render(name, value, attrs, choices)

        style = self.attrs.get('style', None)
        if style:
            output = output.replace("<ul", format_html('<ul style="{0}"', style))

        return mark_safe(output)

然后在你的表单中:

class NewRoleFrom(forms.Form):
    role = forms.ModelMultipleChoiceField(
        queryset=Role.objects.all(),
        widget=CustomCheckboxSelectMultiple(attrs={'style': 'list-style: none; margin: 0;'})
    )

0

这是来自django.forms.widgets模块的小部件源代码:

class CheckboxSelectMultiple(SelectMultiple):
    def render(self, name, value, 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>']
        # 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))

    def id_for_label(self, id_):
        # See the comment for RadioSelect.id_for_label()
        if id_:
            id_ += '_0'
        return id_

你可以看到这些圆点是由于Django列表的CSS造成的。因此,要删除它们,请考虑创建一个新的小部件,继承自CheckboxSelectMultiple,并向“ul”HTML标记添加一个类,然后使用详细解决方案here添加自己的CSS。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接