Skip to content

Instantly share code, notes, and snippets.

@rochacon
Created December 23, 2011 13:32
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rochacon/1514222 to your computer and use it in GitHub Desktop.
Save rochacon/1514222 to your computer and use it in GitHub Desktop.
Easy Django ModelForm widget placeholder
#
# 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})
@asafge
Copy link

asafge commented Jan 14, 2014

Nice

@pakal
Copy link

pakal commented Nov 30, 2016

isinstance() can take a TUPLE of classes as second argument, thus factorizing this code a lot.

@Lofi-Bytes
Copy link

Thanks!

@sunjoomoon
Copy link

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