问题
I have a Django ModelForm where I set certain form attributes in the form __init__()
method.
class MyForm(forms.ModelForm):
class Meta:
model = MyModel
exclude = ['datecreated', 'datemodified']
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['field1'].widget.attrs['class'] = 'class1'
self.fields['field2'].widget.attrs['class'] = 'class1'
self.fields['field3'].widget.attrs['class'] = 'class1'
# override Google Chrome field error issues making form unfocusable
self.fields['field1'].required = False
self.fields['field2'].required = False
self.fields['field3'].required = False
Is there away to set attributes of all fields included in the form without writing self.fields for each one individually?
回答1:
self.fields
is a normal dict, you can just iterate over its values:
for field in self.fields.values():
field.widget.attrs['class'] = 'class1'
field.required = False
来源:https://stackoverflow.com/questions/46283636/set-attribute-of-all-fields-in-django-modelform-in-init-method