Login

Decorator to add placeholders to field

Author:
stani
Posted:
May 12, 2017
Language:
Python
Version:
Not specified
Tags:
decorator placeholder
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 label, field in cls.base_fields.items():
        widget_type = type(field.widget)
        if widget_type == forms.TextInput:
            field.widget = forms.TextInput(attrs={'placeholder': label})
        elif widget_type == forms.Textarea:
            field.widget = forms.Textarea(attrs={'placeholder': label})
    return cls


def add_placeholders_to_any_field(cls):
    """Add placeholders to any field to a Form type."""
    for label, field in cls.base_fields.items():
        field.widget.attrs["placeholder"] = label
    return cls

More like this

Comments

Please login first before commenting.