django multivaluefield& multiwidget - 使一个可选

时间:2012-05-04 18:23:10

标签: django django-models django-multiwidget

这与我的earlier question有关。

我想拥有一个包含Choice和TextInput小部件的MultiValueField。如果用户从Choice中选择“OTHER”,则应保存TextInput的值。否则,应保存Choice的值。到目前为止,我有以下代码:

custom_choices = [("one","one"),("two","two"),("OTHER","OTHER")]

class MyMultiWidget(forms.MultiWidget):
    def __init__(self,*args,**kwargs):
        widgets = (
            forms.Select(choices=custom_choices),
            forms.TextInput(),
        )
        super(MyMultiWidget, self).__init__(widgets,*args,**kwargs)

    def decompress(self, value):
        if value:
             return value.split("|")
        return ['', '']

class MyMultiValueField(forms.MultiValueField):
    def __init__(self, *args, **kwargs):
        fields = (
            forms.CharField(max_length=128,required=True),
            forms.CharField(max_length=128,required=False),
        )
        super(MyMultiValueField, self).__init__(fields, *args, **kwargs)
        self.widget = TestMultiWidget()

    def compress(self, data_list):
        if data_list:
            return '|'.join(data_list)

class MyTestField(models.CharField):
    def formfield(self, **kwargs):
        return super(MyTestField, self).formfield(form_class=MyMultiValueField)

class MyModel(models.Model):
    myField = MyTestField()

但是,每当我尝试保存TextInput中不包含值的内容时,我都会收到验证错误“此字段是必需的”。尽管上面有“required = False”kwarg。

我试图在clean函数中添加一些逻辑;如果Choice小部件的值为“OTHER”,则忽略TextInput的小部件:

def clean(self,value):
    if value[0]!="OTHER":
        value[1]=u''
    else:
        if not value[1]:
            msg = "unspecified value"
            raise forms.ValidationError(msg)
        elif "|" in value[1]:
            msg = "bad value ('|' character is not allowed"
            raise forms.ValidationError(msg)
    super(TestFormField,self).clean(value)

但这没有效果。

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

正确版本的清洁应该是这样的:

def clean(self,value):
    if value[0] != "OTHER":
        value[1] = u' '
    else:
        if value[1].strip() == u' ':
            msg = "unspecified value"
            raise forms.ValidationError(msg)
        elif "|" in value[1]:
            msg = "bad value ('|' character is not allowed)"
            raise forms.ValidationError(msg)
    return "|".join(value)