djangodjango-formsdjango-widgetdjango-widget-tweaks

django apply widget for all fields


Is there a way to apply css class to ALL fields instead of doing the following for every single field.
forms.py

class UserColorsForm(forms.ModelForm):

    class Meta:
        model = UserColors
        exclude = ('userid',)
        widgets = {
            'text_color': forms.TextInput(attrs={'class': 'color'}),
            'background_color': forms.TextInput(attrs={'class': 'color'}),
            ... 10 more
        }

Solution

  • This should work

    def __init__(self, *args, **kwargs):
        super(UserColorsForm, self).__init__(*args, **kwargs)
        for field in self.fields: 
            field.wiget.attrs['class'] = 'color'