Login

Add attrs automaticlly through ModelForm field max_length

Author:
lettoo
Posted:
January 18, 2012
Language:
Python
Version:
Not specified
Tags:
ModelForm Model CSS
Score:
0 (after 0 ratings)
  1. Define a subclass extends forms.ModelForm
  2. Add the init method
  3. Define your ModelForm extends this class
  4. Define the CSS for "large","xlarge" and "xxlarge",or define yourself.
 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 3 years, 6 months ago
  2. Subdirectory and subcontext include template tag with examples by t_rybik 5 years, 1 month ago
  3. change a widget attribute in ModelForm without define the field by jedie 6 years, 9 months ago
  4. Ajax progress bar by ebartels 7 years ago
  5. YUI Autocomplete by pigletto 7 years, 8 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 }

#

Please login first before commenting.