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
.
Right now I have:
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.
What are your suggestions?
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