Skip to content

Instantly share code, notes, and snippets.

@tschwaerzl
Last active December 16, 2015 07:59
Show Gist options
  • Save tschwaerzl/5402873 to your computer and use it in GitHub Desktop.
Save tschwaerzl/5402873 to your computer and use it in GitHub Desktop.
Original source: http://djangosnippets.org/snippets/2650/ (Autor: lettoo) Description: How to automaticaly add css to all fields of a ModelForm
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'})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment