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?
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])
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With