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?
There is much more Django Crispy Forms can do. Hopefully this tutorial gave you some extra insights on how to use the form helpers and layout classes. As always, the official documentation is the best source of information: Also, the code used in this tutorial is available on GitHub at github.com/sibtc/advanced-crispy-forms-examples.
This layout object can be used to easily extend Django’s widgets. If you want to render a Django form field as hidden you can simply do: If you need HTML5 attributes, you can easily do those using underscores data_name kwarg here will become into data-name in your generated html:
label – Django Form Field Validation Last Updated : 13 Feb, 2020 Built-in Form Field Validations in Django Forms are the default validations that come predefined to all fields. Every field comes in with some built-in validations from Django validators.
Just attach the layout to a helper, layouts are optional, but probably the most powerful thing django-crispy-forms has to offer. A Layout is constructed by layout objects, which can be thought of as form components.
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
Currently, hiding labels can be achieved by using the bootstrap helper attribute below:
self.helper.form_show_labels = False
Default set to True. It decides wether to render or not form’s fields labels.
You still need to define the placeholder using the Field layout object:
Field('query', placeholder='Search ...'),
Try this:
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With