- Author:
- stani
- Posted:
- May 12, 2017
- Language:
- Python
- Version:
- Not specified
- Score:
- 2 (after 2 ratings)
Decorator to automagically add placeholders to form widgets. cls can be any class derived from django.forms.Form or django.forms.ModelForm. The field labels are used as value for the placeholder. This will affect all form instances of this class.
- add_placeholders only to forms.TextInput and form.Textarea
- add_placeholders_to_any_field adds placeholders to any field
Usage:
@add_placeholders
class Form(forms.Form):
name = forms.CharField
The name field will render as <input type="text" placeholder="name">
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | def add_placeholders(cls):
"""Add placeholders by widget type to a Form type."""
for field in cls.base_fields.values():
widget_type = type(field.widget)
if widget_type == forms.TextInput:
field.widget = forms.TextInput(attrs={'placeholder': field.label})
elif widget_type == forms.Textarea:
field.widget = forms.Textarea(attrs={'placeholder': field.label})
return cls
def add_placeholders_to_any_field(cls):
"""Add placeholders to any field to a Form type."""
for field in cls.base_fields.values():
field.widget.attrs["placeholder"] = field.label
return cls
|
More like this
- Add Toggle Switch Widget to Django Forms by OgliariNatan 2 months ago
- get_object_or_none by azwdevops 5 months, 3 weeks ago
- Mask sensitive data from logger by agusmakmun 7 months, 3 weeks ago
- Template tag - list punctuation for a list of items by shapiromatron 1 year, 9 months ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 1 year, 10 months ago
Comments
Please login first before commenting.