django-bootstrap-v5 DecimalField Throwing Errors in ModelForm Class

Viewed 125

Using the django-bootstrap-v5 module, I get the error:

"init() got an unexpected keyword argument 'attrs'"

on a DecimalField Widget in the definition of a ModelForm class for a simple Model. The Model is defined as follows:

class MenuItem(models.Model):
    menuname=models.CharField(max_length=20,primary_key=True)
    description=models.TextField()
    price=models.DecimalField(max_digits = 5, decimal_places = 2)

And the Model Form is defined as follows:

class MenuItemForm(forms.ModelForm):
    class Meta:
        model=MenuItem
        fields='__all__'
        widgets = {'menuname': forms.TextInput(attrs={'class': 'form-control'}),
                'description': forms.Textarea(attrs={'class': 'form-control'}),
                'price': forms.DecimalField(attrs={'class': 'form-control'}),
                }

The error is thrown on the Line:

'price': forms.DecimalField(attrs={'class': 'form-control'}),

If I change that line to:

'price': forms.TextInput(attrs={'class': 'form-control'}),

Then no error it thrown. But of course I would rather use a DecimalField widget rather than a TextInput to render the underlying DecimalField in the model.

Once again this is using the django-bootstrap-v5 module.

Any Ideas?

1 Answers

forms.DecimalField is a form field not a widget. The default widget used by DecimalField is NumberInput [Django docs] hence you should use that instead:

class MenuItemForm(forms.ModelForm):
    class Meta:
        model = MenuItem
        fields = '__all__'
        widgets = {'menuname': forms.TextInput(attrs={'class': 'form-control'}),
                'description': forms.Textarea(attrs={'class': 'form-control'}),
                'price': forms.NumberInput(attrs={'class': 'form-control'}),
                }
Related