有没有办法将css类应用于 ALL 字段,而不是为每个字段执行以下操作。
的 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
}
答案 0 :(得分:4)
这应该有效
def __init__(self, *args, **kwargs):
super(UserColorsForm, self).__init__(*args, **kwargs)
for field in self.fields:
field.wiget.attrs['class'] = 'color'
答案 1 :(得分:1)
尝试迭代表单字段:
css1 = {'class': 'color', }
css2 = {'class': 'nocolor', }
class UserColorsForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(UserColorsForm, self).__init__(*args, **kwargs)
for key, value in self.fields.iteritems():
if key in ['field1', 'field2', ...]: # You can define a
# subset of fields in a list to selectively apply css classes,
# OR just iterate and apply to everything
# (take out the if-else statement)
self.fields[key].widget.attrs.update(css1)
else:
self.fields[key].widget.attrs.update(css2)
答案 2 :(得分:0)
要更新Mihai的答案,方法是:
def __init__(self, *args, **kwargs):
super(YourForm, self).__init__(*args, **kwargs)
for field in self.fields:
self.fields[field].widget.attrs.update({'class': 'myfieldclass'})