- 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
- Template tag - list punctuation for a list of items by shapiromatron 10 months ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 1 week ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 5 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.