Created
December 23, 2011 13:32
-
-
Save rochacon/1514222 to your computer and use it in GitHub Desktop.
Easy Django ModelForm widget placeholder
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# This code inserts the placeholder attribute, using the field's label, | |
# for all TextInput, Textarea, DateInput, DateTimeInput, TimeInput widgets | |
# of your ModelForm | |
# | |
class MyForm(forms.ModelForm): | |
class Meta: | |
model = MyModel | |
def __init__(self, *args, **kwargs): | |
super(MyForm, self).__init__(*args, **kwargs) | |
for key, field in self.fields.items(): | |
if isinstance(field.widget, forms.TextInput) or \ | |
isinstance(field.widget, forms.Textarea) or \ | |
isinstance(field.widget, forms.DateInput) or \ | |
isinstance(field.widget, forms.DateTimeInput) or \ | |
isinstance(field.widget, forms.TimeInput): | |
field.widget.attrs.update({'placeholder': field.label}) |
isinstance() can take a TUPLE of classes as second argument, thus factorizing this code a lot.
Thanks!
Many thanks, you saved a bunch of my hair.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice