[Solved]-How can I modify a widget's attributes in a ModelForm's __init__() method?

22👍

def __init__(self, *args, **kwargs):
    super(MyForm, self).__init__(*args, **kwargs)
    self.fields['my_checkbox'].widget.attrs['onclick'] = 'return false;'

4👍

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;'})

1👍

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;'})

0👍

I had to do the same thing, but not necessarily on initialisation. In my case I had to set-up a specific id to work with my AJAX function. The answer was similar to kmctown above, but I didn’t use the init, just created a normal function within the form class as per below:

def type_attr(self, id_val):
    self.fields['type'].widget.attrs.update({'id':id_val})

Then, in views:

form=YourForm(request.POST or None)
form.type_attr(id_val)

This worked in my case.

Leave a comment