问题
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">
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")
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?
Here is my form:
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'))
回答1:
From 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")
So you need to use the keyword data_label_text
instead.
Field('some_field', data_label_text="whatever")
回答2:
From the source code.
# 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()]))
it puts all the kwargs to your form element, so you can do something like.
Field('YOUR_FIELD_NAME', data_label_text="Label")
来源:https://stackoverflow.com/questions/31227692/adding-attribute-to-crispy-forms-django