Set attribute of all fields in Django ModelForm in init method

て烟熏妆下的殇ゞ 提交于 2019-12-24 18:29:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!