Add attrs automaticlly through ModelForm field max_length

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class MyModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(forms.ModelForm, self).__init__(*args, **kwargs)
        for field_name in self.base_fields:
            field = self.base_fields[field_name]
            size = None
            try:
                size = field.max_length
            except:
                size = None
            if size:
                if size > 100:
                    field.widget.attrs.update({'class': 'xxlarge'})
                elif size > 50:
                    field.widget.attrs.update({'class': 'xlarge'})
                else:
                    field.widget.attrs.update({'class': 'large'})
            else:
                field.widget.attrs.update({'class': 'large'})

More like this

  1. ModelForm Class saving m2m by ckarrie2 2 years, 6 months ago
  2. Subdirectory and subcontext include template tag with examples by t_rybik 4 years, 1 month ago
  3. change a widget attribute in ModelForm without define the field by jedie 5 years, 8 months ago
  4. Ajax progress bar by ebartels 6 years ago
  5. Modeli18n by pavl 3 years, 10 months ago

Comments

lettoo (on January 18, 2012):

Update CSS sytle input.large, textarea.large, select.large { width: 210px; }

input.xlarge, textarea.xlarge, select.xlarge { width: 270px; }

input.xxlarge, textarea.xxlarge, select.xxlarge { width: 530px }

#

(Forgotten your password?)