Django-字段验证,以确保数据是浮点元组的列表



我有一个Charfield,用户必须在其中输入浮点元组列表(不带括号),如:(0,1)、(0.43,54)、(24.2,4)

如何确保:首先,输入是元组的列表,其次,元组仅由float组成?

到目前为止我尝试了什么:

def clean_dash_array(self):
    data = self.cleaned_data['dash_array']
    try:
        data_list = eval("[%s]" % data) #transform string into list
        for t in data_list:
            if type(t) != tuple:
                raise forms.ValidationError("If: You must enter tuple(s) of float delimited with coma - Ex: (1,1),(2,2)")
    except:
        raise forms.ValidationError("Except: You must enter tuple(s) of float delimited with coma - Ex: (1,1),(2,2)")
    return data

这并不完整,因为它无法验证元组是否仅包含浮点值。

编辑:

def clean_dash_array(self):
    data = self.cleaned_data['dash_array']
    try:
        data_cleaned = [tuple(float(i) for i in el.strip('()').split(',')) for el in data.split('),(')]
    except:
        raise forms.ValidationError("Except: You must enter tuple(s) of int or float delimited with coma - Ex: (1,1),(2,2)")
    return data

这种干净的方法似乎有效,并且不像Iain Shelvington所建议的那样使用eval()。

你认为这会验证数据是否存在任何类型的错误输入吗?

如果我理解正确,应该这样做:

def clean_dash_array(self):
    data = self.cleaned_data['dash_array']
    for tuple_array in data:
        if type(tuple_array) == tuple:
            for tuple_data in tuple_array:
                if type(tuple_data) == float:
                    #Do something with this
                else:
                    return "Error: Not a float"
        else:
            return "Error: Not a tuple."

此解决方案正在运行:

def clean_dash_array(self):
    data = self.cleaned_data['dash_array']
    try:
        data_cleaned = [tuple(float(i) for i in el.strip('()').split(',')) for el in data.split('),(')]
    except:
        raise forms.ValidationError("You must enter tuple(s) of int or float delimited with commas - Ex: (1,1),(2,2)")
    return data

最新更新