Add a CSS class to every field indicating what kind of field it is

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
def add_css_classes(f, **kwargs):
    """
    Formfield callback that adds a CSS class to every field indicating
    what kind of field it is. For example, all CharField inputs will get
    a class of "vCharField". If the field's widget already has a
    "class" attribute, it will be left alone.

    Example:

    class MyForm(forms.ModelForm):
        formfield_callback = add_css_classes
    """
    field = f.formfield(**kwargs)
    if field and 'class' not in field.widget.attrs:
        field.widget.attrs['class'] = 'v%s' % field.__class__.__name__
    return field

More like this

  1. Read only form & model field by StanislavKraev 1 year, 10 months ago
  2. create or update, then get, model instances from JSON/py dict by anentropic 1 year, 5 months ago
  3. Use JQuery Calendar in ModelForm by Induane 2 years, 10 months ago
  4. Duplicate related objects of model instance by johnboxall 4 years, 4 months ago
  5. Dynamically add css-classes to formfields by Lacour 1 year, 10 months ago

Comments

(Forgotten your password?)