【发布时间】:2010-12-09 16:50:23
【问题描述】:
我有一个带有字符域和选择域的多值域。我需要将选项传递给choicefield 构造函数,但是当我尝试将它传递给我的自定义多值字段时,我收到错误__init__() got an unexpected keyword argument 'choices'。
我知道其余代码可以正常工作,因为当我从 __init__ 和 super 中删除选项关键字参数时,多值字段正确显示但没有任何选项。
这就是我设置自定义多值字段的方式:
class InputAndChoice(object):
def __init__(self, text_val='', choice_val=''):
self.text_val=text_val
self.choice_val=choice_val
class InputAndChoiceWidget(widgets.MultiWidget):
def __init__(self, attrs=None):
widget = (widgets.TextInput(),
widgets.Select()
)
super(InputAndChoiceWidget, self).__init__(widget, attrs=attrs)
def decompress(self,value):
if value:
return [value.text_val, value.choice_val]
return [None, None]
class InputAndChoiceField(forms.MultiValueField):
widget = InputAndChoiceWidget
def __init__(self, required=True, widget=None, label=None, initial=None,
help_text=None, choices=None):
field = (
fields.CharField(),
fields.ChoiceField(choices=choices),
)
super(InputAndChoiceField, self).__init__(fields=field, widget=widget,
label=label, initial=initial, help_text=help_text, choices=choices)
我这样称呼它:
input_and_choice = InputAndChoiceField(choices=[(1,'first'),(2,'second')])
那么如何将选项传递给我的 ChoiceField 字段?
编辑:
我已经尝试了 stefanw 的建议,但仍然没有运气。我使用 logging.debug 在 init 的末尾打印出 InputAndChoiceField 的内容,self.fields[1].choices 包含正确的值,但它不会在浏览器中显示任何选项。
【问题讨论】:
标签: django django-forms django-widget django-models