[Django]-How to add class attribute to ModelForm

5👍

You can do it in __init__ form method:

class TestPoljaForm(ModelForm):
    class Meta:
        model = TestPolja

    def __init__(self, *args, **kwargs):
        super(TestPoljaForm, self).__init__(*args, **kwargs)

        # for example change class for integerPolje1
        self.fields['integerPolje1'].widget.attrs['class'] = 'SOMECLASS'

        # you can iterate all fields here
        for fname, f in self.fields.items():
            f.widget.attrs['class'] = 'SOMECLASS'
👤ndpu

3👍

class TestPoljaForm(ModelForm):
    integerPolje1 =  forms.IntegerField(widget=forms.TextInput(attrs={'class': 'myclass'}))

    class Meta:
        model = TestPolja

Leave a comment