Validate upload of csv files

Asked

Viewed 37 times

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!!

1 answer

0

I believe you can do this in your method forms.py as below

class UploadArquivo(forms.ModelForm):
    EXTENSOES = ['csv']

    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 clean_upload_csv(self):
            arquivo = self.cleaned_data.get('upload_csv', None)
            if arquivo is None:
                raise forms.ValidationError('Faltando arquivo')
            else:
                try:
                    ext = arquivo.name.lower().split(".")[-1]
                    if ext in self.EXTENSOES:
                        return upload_csv
                    else:
                        raise forms.ValidationError('Arquivo não permitido')
                except Exception as e:
                    raise forms.ValidationError('Arquivo sem extensão')

        def clean(self):
            data = super(UploadArquivo, self).clean()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.