lundi 7 juillet 2014

validating file contents when uploading to Django form


Vote count:

0




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.



asked 1 min ago






Aucun commentaire:

Enregistrer un commentaire