Use field label as placeholder in django-crispy-forms

I am thinking of a DRY method for using field labels for the placeholder attribute of my <input> HTML elements. I am using django-crispy-forms .

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 would prefer, however, not to set the label and placeholder separately, since there will still be many fields for this, and this is pretty verbose.

What are your suggestions?

+6
source share
6 answers

A DRY solution can be reached 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 
+11
source

Currently, tag hiding can be achieved using the auxiliary bootstrap attribute below:

self.helper.form_show_labels = False

The default value is True. It decides whether to visualize or not create field labels.

You still need to define the placeholder using the field layout object:

Field ('query', placeholder = 'Search ...'),

+5
source

Try the following:

 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=kwargs.pop('query_placeholder', 'random text')), ) super(FilterForm, self).__init__(data, files, **kwargs) 
+4
source

You can add additional attributes to the form fields using:

 query = CharField(widget=forms.TextInput(attrs={'placeholder':'Search..'}), max_length=50, label='', required=False) 
+1
source

This DRY solution does not require layout modification. I suggest doing this mixin:

 class MyForm(Form): _placeholders = { 'fieldname': 'fieldname placeholder', } def __init__(self, *args, **kwargs): # Assign placeholder to widget of fields # listed in self._placeholders. for field_name, field in self.fields.items(): if field_name in self._placeholders: self.fields[field_name].widget.attrs['placeholder'] = \ self._placeholders[field_name] super(MyForm, self).__init__(*args, **kwargs) 
0
source

In the end, I just hid the field labels using css. This is a bit of hacks, but it works. I still used placeholder = "your shortcut" to define placeholders.

-1
source

All Articles