我可以更改表单小部件类而无需在Django中明确重新定义它吗?

时间:2014-03-15 06:14:27

标签: django django-forms django-widget

我试图更改Django表单字段的类。我的表格如下:

class MyForm(forms.Form):
    my_field = forms.ChoiceField(choices=myChoices)

为什么它只能显式更改Select字段的类?我想要默认的Select小部件,有没有办法在不重新定义的情况下更改它的attrs?这有效:

class MyForm(forms.Form):
    myfield = forms.ChoiceField(choices=myChoices, widget=forms.Select(attrs={'class': 'myclass'}))

但这似乎合乎逻辑且更简单,提出了TypeError: __init__() got an unexpected keyword argument 'attrs'

class MyForm(forms.Form):
    myfield = forms.ChoiceField(choices=myChoices, attrs={'class': 'myclass'})

1 个答案:

答案 0 :(得分:1)

它有更多代码,但如果你真的不想定义小部件类型类,你可以这样做:

class MyForm(forms.Form):
    myfield = forms.ChoiceField(choices=myChoices)

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['myfield'].widget.attrs={'class': 'myclass'}