1

我已经设置了一个用于内联的 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
4

2 回答 2

0

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

于 2011-08-27T14:17:38.063 回答
0

This was my problem, right here:

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

Needed to be changed to

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

If you use None as the value for a choice in a choice field, it gets rendered as

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

instead of

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

Here's the guilty source code in Django (In the Select widget class's render_option method):

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

I can't think of any situation where you'd specify None as a value and want to get "None" back. Although of course the empty value "" is also different than None.

于 2011-08-29T22:45:01.667 回答