Login

Add attrs automaticlly through ModelForm field max_length

Author:
lettoo
Posted:
January 18, 2012
Language:
Python
Version:
Not specified
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. Template tag - list punctuation for a list of items by shapiromatron 9 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 9 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 3 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 4 months ago
  5. Help text hyperlinks by sa2812 1 year, 5 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.