Guy Bowden
Guy Bowden

Reputation: 5107

validating file contents when uploading to Django form

I am trying to validate a CSV file uploaded into Django Admin - to make sure it's in the right format and so on.

It also relies on another value in the form so I am validating it inside the forms clean method:

def clean(self):
    cleaned_data = super(CSVInlineForm, self).clean()
    csv_file = cleaned_data.get('csv_file')
    contents = csv_file.read()
    # ...validate contents here...
    return cleaned_data

My model save method looks like this:

def save(self, *args, **kwargs):
    contents = self.csv_file.read()
    # ... do something with the contents here ...
    return super(CSVModel, self).save(*args, **kwargs)

The problem comes when I read the file contents inside the clean method, I can not read the csv_file inside the model save method (it returns an empty string). Inside the clean method I can read and parse the file.

The file is uploaded perfectly fine and intact.

If I comment out the csv_file.read() line in the clean method, the save method works fine and can read the file contents.

It's behaving as if the file can only be read once?

And if I re-save the model the file reading and parsing works normally.

This is all within django admin - the forms are being handled correctly as far as I can tell.

Upvotes: 2

Views: 1353

Answers (1)

karthikr
karthikr

Reputation: 99620

Since you read the file once with .read(), the file pointer would not point to the end of the file. You would have to reset this if you were to read it again.

You can do this with the seek() function.

So, either after the read() in clean or just before the read() in save method, do

csv_file.seek(0)

Some more info here

Upvotes: 6

Related Questions