Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 307
Huuuze Avatar asked Oct 18 '10 17:10

Huuuze


3 Answers

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;'})
like image 64
James Lin Avatar answered Sep 28 '22 04:09

James Lin


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;'})
like image 32
kmctown Avatar answered Sep 28 '22 03:09

kmctown


def __init__(self, *args, **kwargs):
    super(MyForm, self).__init__(*args, **kwargs)
    self.fields['my_checkbox'].widget.attrs['onclick'] = 'return false;'
like image 38
Bernhard Vallant Avatar answered Sep 28 '22 02:09

Bernhard Vallant