Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django-确保数据是浮点元组列表的字段验证_Python_Django - Fatal编程技术网

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

Python Django-确保数据是浮点元组列表的字段验证,python,django,Python,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 l

我有一个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
这是不完整的,因为它无法验证元组是否只包含float

编辑:

这个干净的方法似乎可以工作,并且不像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

您不应该在用户提供的inputok上运行eval(),谢谢您的建议,使用ast.literal\u eval是否更好?不,永远不会。绝对不是。请不要为了自己的利益而接近这些功能。您正在搜索字符串中的模式,请使用
re
模块,而不是使用良好的建议,请参见编辑。这应该可以工作,您正在将数字转换为
int
,而不是
float
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