MultiValueField在可选的内联中

时间:2011-08-25 21:44:54

标签: django django-forms django-multiwidget

我已经设置了一个在内联中使用的MultiValueField。如果我将MultiValueField留空,它似乎认为它是静止的。因此,我一直得到表单验证错误,因为就表单而言,这些内联不是空的(因此得到验证)。

所以我想我在想:是否有设置MultiValueField的技巧,以便它可以显式空白,以便我可以避免引发验证错误?

以下是相关代码:

class TypedValueField(forms.MultiValueField):
    def __init__(self, *args, **kwargs):
        fields = (
                  forms.ChoiceField(required=False, choices=[(None, '(type)')] + [(c,c) for c in ['int','float','bool','string']]),
                  forms.CharField(required=False)
                  )
        super(TypedValueField, self).__init__(fields, *args, **kwargs)


    def compress(self, data_list):
        if data_list:
            # Raise a validation error if time or date is empty
            # (possible if SplitDateTimeField has required=False).
            if data_list[1]=="" or data_list[1]==None:
                return data_list[1]
            if data_list[0] == 'bool':
                try:
                    if data_list[1].lower() == "true":
                        return True
                except:
                    pass
                try:
                    if int(data_list[1] == 1):
                        return True
                except ValueError:
                    raise forms.ValidationError("You must enter True or False")
                return False
            if data_list[0] == 'int':
                try:
                    return int(data_list[1])
                except ValueError:
                    raise forms.ValidationError("You must enter a number")
            if data_list[0] == 'float':
                try:
                    return float(data_list[1])
                except ValueError:
                    raise forms.ValidationError("You must enter a decimal number")
            if data_list[0] == 'string':
                return data_list[0]
            else:
                raise forms.ValidationError("Invalid data type")
        return None


class TypedValueWidget(forms.MultiWidget):
    def __init__(self, attrs=None):
        widgets = (
            forms.Select(choices=[(None, '(type)')] + [(c,c) for c in ['int','float','bool','string']]),
            forms.TextInput()
        )
        super(TypedValueWidget, self).__init__(widgets, attrs)

    def decompress(self, value):
        if value:
            if isinstance(value, bool):
                return ['bool', value]
            if isinstance(value, float):
                return ['float', value]
            if isinstance(value, int):
                return ['int', value]
            if isinstance(value, basestring):
                return ['string', value]
            else:
                raise Exception("Invalid type found: %s" % type(value))
        return [None, None]

class ParamInlineForm(forms.ModelForm):
    match = TypedValueField(required=False, widget=TypedValueWidget())

    class Meta:
        model = Param

2 个答案:

答案 0 :(得分:0)

覆盖MutliValueField的干净方法 (看看django来源)

答案 1 :(得分:0)

这是我的问题,就在这里:

        fields = (
                  forms.ChoiceField(required=False, choices=[(None, '(type)')] + [(c,c) for c in ['int','float','bool','string']]),
                  forms.CharField(required=False)
                  )

需要更改为

        fields = (
                  forms.ChoiceField(required=False, choices=[("", '(type)')] + [(c,c) for c in ['int','float','bool','string']]),
                  forms.CharField(required=False)
                  )

如果您使用None作为选择字段中的选项值,则会将其呈现为

<option value="None">(type)</option>

而不是

<option value="">(type)</option>

这是Django中的恶意源代码(在Select小部件类的render_option方法中):

        return u'<option value="%s"%s>%s</option>' % (
            escape(option_value), selected_html,
            conditional_escape(force_unicode(option_label)))

我无法想到您将None指定为值并希望获得"None"的任何情况。虽然空值""当然也不同于None