Login

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

Author:
ramen
Posted:
July 6, 2010
Language:
Python
Version:
1.2
Tags:
css field widget modelform callback
Score:
2 (after 2 ratings)

The admin site uses a CSS class for each kind of field so that they can be styled easily. This snippet gives ModelForms a similar feature.

See also: James Bennett's explanation of formfield_callback

 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. Use JQuery Calendar in ModelForm by Induane 4 years, 8 months ago
  2. Dynamically add css-classes to formfields by Lacour 3 years, 7 months ago
  3. Add model form field meta data in a DRY way by jedie 5 years, 11 months ago
  4. Custom CSS class in Form with template tag filter by kegan 5 years, 8 months ago
  5. Add attrs automaticlly through ModelForm field max_length by lettoo 3 years, 1 month ago

Comments

Please login first before commenting.