渲染 Django 表单多项选择

Render django form multiplechoice

我一直在网上搜索如何将 colors/themes 应用到 Django 中的复选框表单项目,但找不到如何操作。

我想做的事情可能很容易,但是尽管我红了所有的话题和博客,我还是做不到。

下面是我的简化表格:

class MyForm(forms.Form):

    def __init__(self, data, *args, **kwargs):
        super(MyForm, self).__init__(data, *args, **kwargs)
        self.fields['checkbox'] = forms.MultipleChoiceField(
            label='Set of questions to know you better',
            required=True,
            widget=forms.CheckboxSelectMultiple(attrs={'disabled': 'disabled'}),
            choices=((1, 'Proposition 1'), (2, 'Proposition 2'), (3, 'Proposition 3'), (4, 'Proposition 4')),
            initial=(1, 2, 4,)
            )

而且我想知道我应该如何修改我的 html 目前看起来像

<form action="{% url 'dummy' %}" method="post">

    {% csrf_token %}
    {{ form.as_p }}

</form>

以便所有 initial 设置为 True 的选项都应用给定的 css到 False 另一个。

希望我的问题有道理。如果没有,请不要犹豫。

最佳:

埃里克

添加当前渲染:

编辑:添加 html 生成的

<form action="/dummy" method="post">

    <input type='hidden' name='csrfmiddlewaretoken' value='LGZ0mwqrAKxb7CzFvOyYIyUIcDSARy4iwEtHVDjKPpnBd1AIXlk4UyxRuCSIEviY' />
    <p><label>Set of questions to know you better :</label> <ul id="id_checkbox">
    <li><label for="id_checkbox_0"><input type="checkbox" name="checkbox" value="1" disabled="disabled" id="id_checkbox_0" checked />
 Proposition 1</label>

</li>
    <li><label for="id_checkbox_1"><input type="checkbox" name="checkbox" value="2" disabled="disabled" id="id_checkbox_1" checked />
 Proposition 2</label>

</li>
    <li><label for="id_checkbox_2"><input type="checkbox" name="checkbox" value="3" disabled="disabled" id="id_checkbox_2" />
 Proposition 3</label>

</li>
    <li><label for="id_checkbox_3"><input type="checkbox" name="checkbox" value="4" disabled="disabled" id="id_checkbox_3" checked />
 Proposition 4</label>

</li>
</ul></p>

</form>

尝试基于 CheckboxSelectMultiple 创建一个新的 Widget,覆盖 create_option 方法。

如果选择了选项,则添加一个新的 class 属性。

def create_option(self, name, value, label, selected, index, subindex=None, attrs=None):
    [..]
    if selected:
        option_attrs.update(self.checked_attribute)
        # add your class here to option_attrs
    [..]

如果你需要样式检查输入,你可以只使用CSS伪class:checked,这样:

input:checked {
  /*some code here */
}

但是,如果您需要有条件地将 class 添加到您的输入中,您可以在实例化表单并覆盖 create_option 方法的视图中执行此操作,但我认为创建它更容易自定义模板标签并使用它。您可以尝试以下操作:

from django import template

@register.filter
def add_css(checkbox_input):
    checkbox_input.data['attrs'].update({"class":"your-class"})
    return checkbox_input

然后在模板中

{% for x in form.checkbox %}
    {% if x.data.selected %}
        {{ x|add_css }}
    {% else %}
       {{ x }}
    {% endif %}
{% endfor %}