覆盖FileField以验证CSV输入文件。有一个表单,并尝试为用户提供以逗号分隔的CharField和大型请求作为CSV输入简单查询的选项。我已经尝试过required = False但是我不确定如何在override方法中传递它。
理想情况下,如果CharField和FileField都为空,我希望显示错误“输入内容”,如果FileField为空则处理CharField,如果填充了FileField,则始终处理它。
非常感谢任何帮助或指示。
forms.py
class userGroupForm(forms.Form):
userGroup_entryList = MultiEntryField(max_items=10)
userGroup_entryFile = CSVFileField(max_items=40)
userGroup_queryType = forms.ChoiceField(choices=(('User','User'),('Group','Group')))
userGroup_sourceType = forms.ChoiceField(choices=(('Corp','Corp'),('Prod','Prod')))
fields.py
class MultiEntryField(forms.Field):
def __init__(self, *args, **kwargs):
self.max_items = kwargs.pop("max_items")
super(MultiEntryField,self).__init__(*args,**kwargs)
def to_python(self,value):
if not value:
return []
else:
entries = []
for entry in value.split(','):
entries.append(entry.replace(' ',''))
return entries
def validate(self,items):
super(MultiEntryField, self).validate(items)
if len(items) > self.max_items:
raise forms.ValidationError('ERROR - More than '+str(self.max_items)+' items')
for item in items:
if re.search('[^a-zA-Z0-9-_/.]',str(item)):
raise forms.ValidationError('ERROR - Only alphanumeric characters')
class CSVFileField(forms.FileField):
def __init__(self, *args, **kwargs):
self.max_items = kwargs.pop("max_items")
super(CSVFileField,self).__init__(*args,**kwargs)
def validate(self,file):
super(CSVFileField, self).validate(file)
if file:
if file._size >= 5000:
raise forms.ValidationError('ERROR - File bigger than 5KB')
if file.content_type not in ['application/vnd.ms-excel'] or os.path.splitext(file._name)[1] not in [".csv"]:
raise forms.ValidationError('ERROR - Not a CSV file')
try:
fileReader = csv.reader(file.file)
except:
raise forms.ValidationError('ERROR - Problem reading file')
fileList = []
for row in fileReader:
fileList.append(row[0])
if len(fileList) > self.max_items:
raise forms.ValidationError('ERROR - More than '+str(self.max_items)+' items')
for item in fileList:
if re.search('[^a-zA-Z0-9-_/.]',str(item)):
raise forms.ValidationError('ERROR - Only alpanumeric characters')
else:
raise forms.ValidationError('ERROR - No file to process')