将属性添加到 crispy forms django

Adding Attribute to crispy forms django

我正在使用 bootstrap 开关,如果我想添加标签,我需要:

<input name="switch-labelText" type="checkbox" data-label-text="Label">

我正在使用 crispy 表单,我可以看到我可以像这样使用 Field 添加属性:

Field('field_name', css_class="black-fields")

这一切对我来说都很有意义,但我似乎无法添加数据标签文本。所以我的问题是我可以用脆皮形式制作自定义属性吗?

这是我的表格:

class InstanceCreationForm(forms.Form):
    some_field = forms.BooleanField(required=False)
    some_field2 = forms.BooleanField(required=False)
    some_field3 = forms.BooleanField(required=False)

    def __init__(self, *args, **kwargs):
        super(InstanceCreationForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_show_labels = False
        self.helper.layout = Layout(
            #This is a syntax error
            Field('some_field', data-label-text="whatever")
        )
        self.helper.add_input(Submit('submit', 'Submit'))

来自the docs

If you want to set html attributes, with words separated by hyphens like data-name, as Python doesn’t support hyphens in keyword arguments and hyphens are the usual notation in HTML, underscores will be translated into hyphens, so you would do: Field('field_name', data_name="whatever")

因此您需要使用关键字 data_label_text 来代替。

Field('some_field', data_label_text="whatever")

来自源代码。

    # We use kwargs as HTML attributes, turning data_id='test' into data-id='test'
    self.attrs.update(dict([(k.replace('_', '-'), conditional_escape(v)) for k, v in kwargs.items()]))

它把所有的 kwargs 放到你的表单元素中,所以你可以做类似的事情。

Field('YOUR_FIELD_NAME', data_label_text="Label")