我会用自定义类覆盖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;'})
)