【问题标题】:How can I write widget for horizontal displaying multiple checkbox?如何编写用于水平显示多个复选框的小部件?
【发布时间】:2019-08-28 11:24:50
【问题描述】:

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

但我不知道如何将其结合起来。

【问题讨论】:

    标签: python django django-widget


    【解决方案1】:

    您正在寻找正确的东西。可以看到,默认的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 模板,它只是包装了一组选项(默认情况下是 &lt;ul&gt;&lt;li&gt;...)。 checkbox_option.html 模板实际上是用于每个选项的模板,您可以在其中放置不带 for 循环的引导代码。

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

    【讨论】:

    • 我这样做了,只是将最里面的 &lt;li&gt; 标签更改为 &lt;span&gt;,现在它是一个紧凑的水平布局,但每个组(如果有的话)将在自己的行上。
    猜你喜欢
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 2021-01-16
    • 1970-01-01
    • 1970-01-01
    • 2021-10-26
    • 2022-06-23
    • 1970-01-01
    相关资源
    最近更新 更多