Add attrs automaticlly through ModelForm field max_length
- Author:
- lettoo
- Posted:
- January 18, 2012
- Language:
- Python
- Version:
- Not specified
- Score:
- 0 (after 0 ratings)
- Define a subclass extends forms.ModelForm
- Add the init method
- Define your ModelForm extends this class
- 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'})
|
Comments
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.