3

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 Answer 1

8

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.