How can I modify a widget's attributes in a ModelForm's __init__() method?
11,711
Solution 1
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['my_checkbox'].widget.attrs['onclick'] = 'return false;'
Solution 2
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;'})
Solution 3
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;'})
Comments
-
Huuuze almost 2 years
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?