【发布时间】:2021-03-17 07:53:12
【问题描述】:
我有一个表格,提供了注册邮件列表的选项。
field = forms.ModelMultipleChoiceField(
queryset=MailingList.objects.filter(
list_active=True),
widget=forms.CheckboxSelectMultiple(
{'class': 'no-bullet-list',
'style': 'list-style: none;'}))
# Specifying class and style both is excessive, I'm still exploring.
同时,我已将其放入我的 CSS 表中:
.no-bullet-list {
list-style-type: none;
}
这就是我想要的,将一组正确的选择呈现为复选框,但它也会在它们之前放置项目符号。这是因为呈现的 HTML 看起来像这样:
<ul id="id_newsletters" class="no-bullet-list">
<li><label for="id_newsletters_0">
<input type="checkbox" name="newsletters" value="1"
class="no-bullet-list" style="list-style: none;"
id="id_newsletters_0">
Annonces</label>
</li>
那个sn-p来自django/forms/templates/django/forms/widgets/multiple_input.html,是CheckboxSelectMultiple在django/forms/widgets.py中定义的结果。
class CheckboxSelectMultiple(ChoiceWidget):
allow_multiple_selected = True
input_type = 'checkbox'
template_name = 'django/forms/widgets/checkbox_select.html'
option_template_name = 'django/forms/widgets/checkbox_option.html'
def use_required_attribute(self, initial):
# Don't use the 'required' attribute because browser validation would
# require all checkboxes to be checked instead of at least one.
return False
def value_omitted_from_data(self, data, files, name):
# HTML checkboxes don't appear in POST data if not checked, so it's
# never known if the value is actually omitted.
return False
def id_for_label(self, id_, index=None):
""""
Don't include for="field_0" in <label> because clicking such a label
would toggle the first checkbox.
"""
if index is None:
return ''
return super().id_for_label(id_, index)
我尝试将 CSS 属性添加到 <li> 仅成功添加到 <ul> 和 <input ...>,因此它没有达到我想要的效果(删除项目符号)。此外,似乎没有自定义挂钩来设置 <li> 的样式。
我看到的唯一方法是将完整的小部件定义及其模板复制到我的应用程序并修改它们。这很恶心。是否有一种可移植的方式来设置复选框列表项的样式?
FWIW,我自己的模板是这样做的:
<form method="post">{% csrf_token %}
<p>{{ form.non_field_errors }}</p>
{% for field in form %}
<p>
{{ field.label }}<br>
{{ field }}
{% if field.help_text %}
<small style="color: grey">{{ field.help_text }}</small>
{% endif %}
</p>
{% for error in field.error_messages %}
<p style="color: red">{{ error }}</p>
{% endfor %}
{% endfor %}
<button type="submit" class="btn btn-outline-primary">Je m'inscris</button>
</form>
【问题讨论】:
-
你确定你正确加载了css吗?由于缓存,这本身并非如此。
标签: django django-forms