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 1 year, 8 months ago
  2. change a widget attribute in ModelForm without define the field by jedie 4 years, 10 months ago
  3. filtered ModelChoiceField queries by robharvey 5 years, 3 months ago
  4. Reorder fields directly in the ModelForm by HM 5 years, 1 month ago
  5. YUI Autocomplete by pigletto 5 years, 9 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?)