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

天大地大妈咪最大 提交于 2019-12-18 15:16:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!