2

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.

2
  • You might have to reset the seek - basically, self.csv_file.seek(0) after the read() Commented Jul 7, 2014 at 14:04
  • spot on - thanks. If you put this as an answer I'll tick it! Commented Jul 7, 2014 at 14:10

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

2 Comments

You are a God among men, for 1,5h I have been trying to find out why after I opened a file for validation it shows as: ' ', when I actually perform operations on it. THANK YOU!
Spent almost a day on figuring out why the read() was not fetching out the file contents. Thanks a ton @karthikr

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.