gpt4 book ai didi

python - 如何编写用于水平显示多个复选框的小部件?

转载 作者:行者123 更新时间:2023-11-28 16:56:45 27 4
gpt4 key购买 nike

我有一个带有多个复选框的表单。但默认情况下它们是垂直显示的。我想水平显示它们。我需要为此任务创建自定义小部件。我找到了 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 表单

{% 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仅包装选项组的模板(在默认情况下为 <ul><li>... )。 checkbox_option.html模板实际上是用于每个选项的模板,您可以在其中放置没有 for 循环的 Bootstrap 代码。

您需要查看 input.html模板以及 Django 包含在 checkbox_option.html 中的模板模板以了解您可以使用的各种小部件变量(如 widget.namewidget.attrs.id 等...)。

关于python - 如何编写用于水平显示多个复选框的小部件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57691296/

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