Login

Decorator to add placeholders to field

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

  1. Image compression before saving the new model / work with JPG, PNG by Schleidens 5 days, 21 hours ago
  2. Help text hyperlinks by sa2812 1 month ago
  3. Stuff by NixonDash 3 months, 1 week ago
  4. Add custom fields to the built-in Group model by jmoppel 5 months, 1 week ago
  5. Month / Year SelectDateWidget based on django SelectDateWidget by pierreben 8 months, 3 weeks ago

Comments

Please login first before commenting.