__init__() got an unexpected keyword argument 'attrs'

Question:

forms.py:

class ImportExcelForm(Form):
    file  = forms.FileField(attrs={'class':'rounded_list',})

I’m trying to add css class to my filefield in forms.I am getting this error "__init__() got an unexpected keyword argument 'attrs'"

What did I do wrong?

Thanks.

Asked By: user2086641

||

Answers:

attrs is not an argument to the field, it’s an argument to the widget.

file = forms.FileField(widget=forms.FileInput(attrs={'class': 'rounded_list'}))

Note that some browsers don’t allow styling of the file input.

Answered By: Daniel Roseman

Even though the solution posted by @Daniel Roseman is also the one recommended in Django docs, it still didn’t work for me. What worked for me is the following:

class ImportExcelForm(Form):
    file  = forms.FileField()
    file.widget.attrs.update({'class': 'rounded_list'})
Answered By: Milosz

I got the same error when using the form field forms.IntegerField() for "widgets" as shown below:

class OrderForm(forms.ModelForm):
    class Meta:
        widgets = {           # Here
            'quantity': forms.IntegerField(attrs={
                'size':'4',
                'max': '99',
                'min': '1',
            }),
        }

So, I changed it to the widget forms.NumberInput() for "widgets" as shown below, then, the error was solved:

class OrderForm(forms.ModelForm):
    class Meta:
        widgets = {           # Here
            'quantity': forms.NumberInput(attrs={   
                'style': 'width:6ch',
                'max': '99',
                'min': '1',
            }),
        }

In addition, I could also use the widget forms.TextInput() for "widgets" as shown below, then, the error was also solved:

class OrderForm(forms.ModelForm):
    class Meta:
        widgets = {           # Here
            'quantity': forms.TextInput(attrs={
                'type': 'number',  
                'style': 'width:6ch',
                'max': '99',
                'min': '1',
            }),
        }          
Answered By: Kai – Kazuya Ito