MultiValueField in an optional inline

518 views Asked by At

I've set up a MultiValueField that's used in an inline. If I leave the MultiValueField blank, it appears to think that it's stilled filled in. As a result, I keep getting form validation errors because as far as the form is concerned those inlines aren't empty (and so get validated).

So I guess I'm wondering: are there tricks to setting up the MultiValueField so that it can be explicitly blank, so that I can avoid raising a validation error?

Here's the code in question:

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

There are 2 answers

1
hovno On

override clean method of MutliValueField
(take a look into django source)

0
Jordan Reiter On

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.