#python #python-3.x #django #csv #django-forms
#python #python-3.x #django #csv #django-формы
Вопрос:
В моем администраторе Django я загружаю CSV-файл и загружаю его. у меня есть два столбца Test case ID и Summary.
Test Case ID,Summary
TC-1,Verify that Process CSV sub module is displayed under “Process CSV” module on Dashboard of Client’s user.
TC-2,Verify that Process CSV sub module is displayed under “Process CSV” module on Dashboard of Client’s user.
TC-3,Verify the dashboard.
TC-4,“verify that user is able to update 'active' attribute 'false ' on adding “new category records” using 'v3/definition/categories' PUT API on specifying the 'active' attribute 'true'”
TC-5,“verify that user is able to update 'active' attribute 'true ' on adding “new category records” using 'v3/definition/categories' PUT API on specifying the 'active' attribute 'false'”
Я хочу добавить проверку, например, если данные под идентификатором тестового примера пусты, должно быть сообщение об ошибке «Все сводки должны иметь соответствующий идентификатор тестового примера’
Я добавил проверку для заголовков.например, если заголовок отсутствует, но вы не знаете, как добавить проверку данных в соответствующие заголовки.
Forms.py
class CsvUpload(forms.Form):
csv_file = forms.FileField()
def clean_csv_file(self):
# Probably worth doing this check first anyway
value = self.cleaned_data['csv_file']
if not value.name.endswith('.csv'):
raise forms.ValidationError('Invalid file type')
try:
data = pd.read_csv(
value.file, encoding='ISO-8859-1', engine='python')
data.columns = data.columns.str.strip().str.lower()
data = data.rename(columns={'test case id': 'Test Case ID'})
def transform(df):
my_new_string = re.sub('[^a-zA-Z0-9"''-_“” n.]', '', df)
return my_new_string
data['summary'] = data['summary'].apply(transform)
except KeyError:
raise forms.ValidationError(
'CSV file must have "Summary" column and "Test Case ID" column')
except Exception as e:
print('Error while parsing CSV file=> %s', e)
raise forms.ValidationError('Failed to parse the CSV file')
return data
def csv_content_validator(csv_file):
# Probably worth doing this check first anyway
if not csv_file.name.endswith('.csv'):
raise forms.ValidationError('Invalid file type')
decoded_file = csv_file.read().decode('ISO-8859-1').splitlines()
reader = csv.DictReader(decoded_file)
headers = []
# for row in csv.DictReader(csv_file, delimiter=',', quotechar='|'):
for row in reader:
headers = [x.lower() for x in list(row.keys())]
break
if 'summary' not in headers or 'test case id' not in headers:
raise forms.ValidationError(
'CSV file must have "Summary" column and "Test Case ID" column')
class AICSVFileForm(forms.ModelForm):
file = forms.FileField(
validators=[csv_content_validator]
)
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
super().__init__(*args, **kwargs)
self.fields['file'].widget.attrs.update({'class': 'form-control'})
self.fields['threshold'].widget.attrs.update({'class': 'form-control'})
self.fields['threshold'].label = "Duplicacy Level"
def save(self, *args, **kwargs):
kwargs['commit'] = False
obj = super().save(*args, **kwargs)
if self.request:
obj.user = self.request.user
obj.original_filename = obj.file.name
obj.save()
return obj
class Meta:
model = AICSVFile
fields = ['file', 'threshold']