0
I have a small form where I ask the user to insert a csv file, however if the user inserts a file with different format he simply lets it pass. I’ve tried everything, but I’m not getting it done. Follow the code below:
Filing cabinet forms.py
:
from django.forms import forms
from django import forms
from parte1.models import PresencaProf
from parte1.models import PresencaAula
class UploadArquivo(forms.ModelForm):
class Meta:
model = PresencaProf
fields = ('evento', 'data', 'upload_csv',)
def __init__(self, *args, **kwargs):
super(UploadArquivo, self).__init__(*args, **kwargs)
for visible in self.visible_fields():
visible.field.widget.attrs['class'] = 'form-control'
# Funcao para validar extensao csv
def valida_csv_extensao(value):
if not value.formulario.endswith('.csv'):
raise forms.ValidationError("Erro!\nApenas arquivos .csv !")
def clean(self):
data = super(UploadArquivo, self).clean()
Filing cabinet views.py
:
def presenca(request):
lista = list()
form = UploadArquivo()
if request.method == 'POST':
formulario = UploadArquivo(request.POST, request.FILES)
data_evento ='-'.join(formulario.data['data'].split('/')[::-1])
if formulario.is_valid():
formulario.save(commit=False)
formulario.save()
arquivo = str(request.FILES.getlist('upload_csv')[0])
f = open('csv/'+arquivo.replace(' ','_'), 'r')
for line in f:
line = line.split(',')
participante = Professor.objects.filter(email_professor=line[1])
if participante:
verifica = PresencaAula.objects.filter(fk_professor__email_professor=line[1], data_aula=data_evento)
if not verifica:
presenca = PresencaAula(fk_professor=participante[0], data_aula=data_evento).save()
# print(line[1])
if line[1]=="":
lista.append(line[0] + ' <strong style="color: #FF0000">| Email não encontrado</strong>')
else:
lista.append(line[1])
f.close()
return render(request, 'upload.html', locals())
My last attempt was to create a function using the .endswith
, but he’s shooting a mistake:
(...) line 34, in presenca
participante = Professor.objects.filter(email_professor=line[1])
IndexError: list index out of range
I really appreciate it if someone can help me!!!