Skip to content

Instantly share code, notes, and snippets.

@bmispelon
Created April 27, 2015 22:03
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bmispelon/c1cbf4de3c576fc21241 to your computer and use it in GitHub Desktop.
Save bmispelon/c1cbf4de3c576fc21241 to your computer and use it in GitHub Desktop.
Automatic placeholder attributes from field labels in Django forms
from functools import partial
def placeholderify(form=None, fields=None):
"""
A decorator for Django forms that sets a `placeholder` attribute to all
fields. Each field's label is used as a placeholder.
Use it like so:
@placeholderify
class MyForm(forms.Form):
name = forms.CharField(label='Your name')
email = forms.EmailField(label='Your email')
Doing that, the `name` field will render like so:
<input ... placeholder="Your name">
"""
if form is None:
return partial(placeholderify, fields=fields)
class WrappedForm(form):
def __init__(self, *args, **kwargs):
super(WrappedForm, self).__init__(*args, **kwargs)
if fields is None:
override = self.fields.values()
else:
override = [field for name, field in self.fields.items() if name in fields]
for field in override:
field.widget.attrs.setdefault('placeholder', field.label)
return WrappedForm
@santutu
Copy link

santutu commented Jan 17, 2019

very useful

@onclefranck
Copy link

Awesome!!!, not only it proposes an elegant solution, I also got an effective crash course on how to make a decorator. Many thanks :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment