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. codigo alto nivel by MrRocklion 1 month ago
  2. Load template from specific app by Krzysiek555 1 month, 3 weeks ago
  3. PostgreSQL JSON subqueries by dolamroth 1 month, 3 weeks ago
  4. "Magic Link" Management Command by webology 6 months, 4 weeks ago
  5. Closest ORM models to a latitude/longitude point by simonw 6 months, 4 weeks ago

Comments

Please login first before commenting.