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


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


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


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):

Then, in views:

form=YourForm(request.POST or None)

This worked in my case.

Leave a comment