views:

16

answers:

1

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?

+1  A: 
def __init__(self, *args, **kwargs):
    super(MyForm, self).__init__(*args, **kwargs)
    self.fields['my_checkbox'].widget.attrs={'onclick':'return false;'}
lazerscience
or, better, `attrs['onclick'] = 'return false'`
Daniel Roseman
Thanks -- that worked. Any idea what "widget_attrs" is meant to do?
Huuuze
@Daneil, can you expound on that?
Huuuze
`widget_attrs` is a method on the field class which is used to return attributes that should be added to the widget, based on the current field class, eg. `max_length` for `CharFields`. You shouldn't overwrite it the way you tried to, because it is necessary to have the field working correctly...
lazerscience