1

这与我之前的一个问题有关。

我想要一个包含 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)

但这没有效果。

有什么建议么?

4

1 回答 1

0

正确版本的 clean 应该如下所示:

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)
于 2012-05-07T14:13:31.413 回答