在django-crispy-forms中使用字段标签作为占位符 [英] Use field label as placeholder in django-crispy-forms
本文介绍了在django-crispy-forms中使用字段标签作为占位符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在考虑使用DRY方法将字段标签用于我的< input>
HTML元素的占位符属性.我正在使用 django-crispy-forms
.
I'm thinking about the DRY way to use field labels for placeholder attribute of my <input>
HTML elements. I'm using django-crispy-forms
.
现在我有:
class FilterForm(Form):
query = CharField(max_length=50, label='', required=False)
def __init__(self, data=None, files=None, **kwargs):
self.helper = FormHelper()
self.helper.layout = Layout(
Field('query', placeholder='Search ...'),
)
super(FilterForm, self).__init__(data, files, **kwargs)
但是,我希望不必分别设置标签和占位符,因为这样做最终将具有更多的字段,而且非常冗长.
I'd prefer, however, not to have to set label and placeholder separately, as this for will eventually have many more fields and it's quite verbose.
您有什么建议?
推荐答案
使用此 __ init __ 方法可以实现DRY解决方案:
A DRY solution could be achieved with this __init__ method:
def __init__(self, *args, **kwargs):
super(FilterForm, self).__init__(*args, **kwargs)
helper = self.helper = FormHelper()
# Moving field labels into placeholders
layout = helper.layout = Layout()
for field_name, field in self.fields.items():
layout.append(Field(field_name, placeholder=field.label))
helper.form_show_labels = False
这篇关于在django-crispy-forms中使用字段标签作为占位符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文