首页 > 解决方案 > 如何编写用于水平显示多个复选框的小部件?

问题描述

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

但我不知道如何团结起来。

标签: pythondjangodjango-widget

解决方案


你正在寻找正确的东西。如您所见,默认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.namewidget.attrs.id...)。


推荐阅读