Use field label as placeholder in django-crispy-fo

2019-06-18 16:14发布

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?

7条回答
Juvenile、少年°
2楼-- · 2019-06-18 17:06

You can add extra attributes to your form fields by using:

query = CharField(widget=forms.TextInput(attrs={'placeholder':'Search..'}),
                  max_length=50, label='', required=False)
查看更多
登录 后发表回答