I want to programatically modify the widget attributes of a field in a Django ModelForm's init() method. Thus far, I've tried the following
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['my_checkbox'].widget_attrs(forms.CheckboxInput(attrs={'onclick':'return false;'}))
Unfortunately, this does not work. Any thoughts?
Bernhard's answer used to work on 1.7 and prior, but I couldn't get it to work on 1.8.
However this works:
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['my_checkbox'].widget = forms.widgets.Checkbox(attrs={'onclick': 'return false;'})
I encountered the same problem as James Lin on Django 1.10, but got around it by updating the attrs
dictionary rather than assigning a new widget instance. In my case, I couldn't guarantee the attribute key existed in the dictionary.
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['my_checkbox'].widget.attrs.update({'onclick': 'return false;'})
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['my_checkbox'].widget.attrs['onclick'] = 'return false;'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With