更改Django表单字段小部件属性,而无需单独执行每个字段?

时间:2016-08-09 13:13:27

标签: django django-forms

如何为所有这些字段设置类?

def __init__(self, *args, **kwargs):
    super(UserForm, self).__init__(*args, **kwargs)
    self.fields['username'].widget.attrs['class'] = 'form-control input-lg'
    self.fields['email'].widget.attrs['class'] = 'form-control input-lg'
    self.fields['first_name'].widget.attrs['class'] = 'form-control input-lg'
    self.fields['last_name'].widget.attrs['class'] = 'form-control input-lg'

看起来不太好。如何更改所有字段而无需分别为每个字段键入?

1 个答案:

答案 0 :(得分:0)

for field in self.fields:
    field.widget.attrs['class'] = 'form-control input-lg'