问题
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:
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['my_checkbox'].widget.attrs['onclick'] = 'return false;'
回答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;'})
回答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;'})
来源:https://stackoverflow.com/questions/3961946/how-can-i-modify-a-widgets-attributes-in-a-modelforms-init-method