Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Django to check if data in TSV/CSV format (not by extension)

In my models.py I have the following CharField

class Method1(models.Model):
    inputfile_param     = models.FileField()

I'd like my web app to check the following condition of the input file:

  • Check if the input file in TSV or CSV or Excel format

  • The first and second column of the input file should not be in numeric format. (excluding the header title of course).

Is there an elegant way to achieve that with Django/Python?

like image 237
neversaint Avatar asked Oct 31 '25 20:10

neversaint


1 Answers

You can add a custom validator to your FileField, where you can do these checks. Something along these lines:

import csv
from django.core.exceptions import ValidationError


def validate_csv(value):
    # Probably worth doing this check first anyway
    if not value.name.endswith('.csv'):
        raise ValidationError('Invalid file type')

    with open(value.file, 'r') as csvfile:
        try:
            csvreader = csv.reader(csvfile)
            # Do whatever checks you want here
            # Raise ValidationError if checks fail
        except csv.Error:
            raise ValidationError('Failed to parse the CSV file')


class Method1(models.Model):
    inputfile = models.FileField(validators=[validate_csv])
like image 199
solarissmoke Avatar answered Nov 03 '25 09:11

solarissmoke