I often use Django form fields with various lengths. I would like to create a custom form field class MyFloatField
with a dynamic widget attribute so I could set the max_width
when defining each form field such as:
quantity = MyFloatField(label='Quantity:', max_width='50px')
price = MyFloatField(label='Price:', max_width='100px')
I have already created a custom form field where the max_width
is a constant.
class MyFloatField(forms.FloatField):
def widget_attrs(self, widget):
attrs = super().widget_attrs(widget)
attrs.setdefault("style", 'max-width: 50px')
return attrs
I assume that in order to make it dynamic (pass the value from field definition) I need to somehow get the argument max_width='100px'
from the definition of the form field and pass it as a variable to the attrs.setdefault()
. I have tried the following but I get a TypeError: __init__() got an unexpected keyword argument 'max_width'
error.
class MyFloatField(forms.FloatField):
def widget_attrs(self, widget):
my_max_width = kwargs['max_width']
attrs = super().widget_attrs(widget)
attrs.setdefault("style", 'max-width: '+my_max_width)
return attrs
Any help would be greatly appreciated.