python - 如何编写用于水平显示多个复选框的小部件?
问题描述
我有一个带有多个复选框的表单。但默认情况下它们是垂直显示的。我想水平显示它们。我需要为此任务创建自定义小部件。我找到了一个默认代码 CheckboxSelectMultiple
https://github.com/django/django/blob/master/django/forms/widgets.py#L765
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)
使用 django 小部件链接到 git
https://github.com/django/django/tree/master/django/forms/templates/django/forms/widgets
我还发现bootstrap
了用于水平显示的表格multiple checkboxes
{% for ... %}
<div class="form-check form-check-inline">
<input type="checkbox" class="form-check-input" id="materialInline{{ .id}}">
<label class="form-check-label" for="materialInline{{ .id}}">{{ .title}}</label>
</div>
{% endfor %}
但我不知道如何团结起来。
解决方案
你正在寻找正确的东西。如您所见,默认CheckboxSelectMultiple
使用这两个模板:
template_name = 'django/forms/widgets/checkbox_select.html'
option_template_name = 'django/forms/widgets/checkbox_option.html'
因此,您唯一需要做的就是使用您自己的小部件对其进行子类化,并根据自己的喜好更改模板:
class HorizontalCheckboxSelectMultiple(CheckboxSelectMultiple):
template_name = 'my_app/widgets/checkbox_select.html'
option_template_name = 'my_app/widgets/checkbox_option.html'
checkbox_select.html
模板实际上是仅包装选项组的multiple_input.html
模板(在默认情况下为 a <ul><li>...
)。该checkbox_option.html
模板实际上是用于每个选项的模板,您可以在其中放置没有 for 循环的引导代码。
您还需要查看input.html
模板以及 Django 包含在模板中的checkbox_option.html
模板,以了解您可以使用的各种小部件变量(例如widget.name
等widget.attrs.id
...)。
推荐阅读
- python-3.x - 如何使用python一次从一个文件夹中裁剪多个图像?
- sql - 在SQL中按日期排序查找每个组中第一次出现的倍数
- python-3.x - Python3.7 asyncio启动webserver(FastAPI)和aio_pika消费者
- c# - 无法删除第二个或第三个选定索引
- powershell - 将 AD 用户信息通过管道传输到 CSV
- javascript - 使用 Jquery 和 Ajax 以及 json 文件从下拉列表中动态选择
- android - 如果hintEnabled false,TextinputLayout 无法正确显示样式
- mysql - CloudSQL 只读副本 - 无法执行停止从属,跳过命令
- javascript - 我从地图函数中获取空项目而不是有条件创建的项目
- google-analytics - 将加载旧版本的容器