将属性添加到脆皮形式的Django [英] Adding Attribute to crispy forms django
问题描述
大家好,我正在使用引导程序开关,看来我想添加标签需要:
Hey guys I am using bootstrap switch and it looks like if I want to add a label I need to:
<input name="switch-labelText" type="checkbox" data-label-text="Label">
我使用的是脆皮表格,可以看到我可以使用Field来添加属性,如下所示:
I am using crispy forms and I can see that I can do add attribute using the Field like so:
Field('field_name', css_class="black-fields")
这对我来说都有意义,但我似乎无法添加data-label-text。所以我的问题是我可以使用酥脆的表格制作自定义属性吗?
This all makes sense to me but I can't seem to add data-label-text. So my question is can I make a custom attribute with crispy forms?
这是我的表格:
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'))
推荐答案
来自文档:
如果要设置html属性,并用连字符(如 data-name
)隔开,因为Python在关键字参数中不支持连字符和连字符是HTML中的常用符号,下划线将转换为连字符,因此您可以这样做:
Field('field_name',data_name = whatever)
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
。
So you need to use the keyword data_label_text
instead.
Field('some_field', data_label_text="whatever")
这篇关于将属性添加到脆皮形式的Django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!