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
override clean method of
MutliValueField
(take a look into django source)