0
I have a form that one of the fields asks for a file. The point is that only files . csv should be allowed, but I’m not getting the validation. Follow the code below with my last attempt.
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():
if not PresencaProf.upload_csv.endswith('.csv'):
raise ValidationError(u'Error message')
else:
formulario.save(commit=False)
formulario.save()
Filing cabinet models.py
:
class PresencaProf(models.Model):
data = models.DateField()
evento = models.ForeignKey(Eventos, on_delete=models.RESTRICT)
# validators=[FileExtensionValidator(['csv'] -> valida um csv
upload_csv = models.FileField(upload_to='csv', blank=True, null=True)
class Meta:
verbose_name = "Regristo de presença"
verbose_name_plural = "Registros de presenças"
Filing cabinet forms.py
:
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()
Thanks for your attention!!