Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django form validation, clean(), and file upload

Can someone illuminate me as to exactly when an uploaded file is actually written to the location returned by "upload_to" in the FileField, in particular with regards to the order of field, model, and form validation and cleaning?

Right now I have a "clean" method on my model which assumes the uploaded file is in place, so it can do some validation on it. It looks like the file isn't yet saved, and may just be held in a temporary location or in memory. If that is the case, how do I "open" it or find a path to it if I need to execute some external process/program to validate the file?

Thanks,

Ian

like image 719
IanSR Avatar asked Feb 17 '11 23:02

IanSR


1 Answers

What do you need to do on it? If your validation will work without a temporary file, you can access the data by calling read() on what your file field returns.

def clean_field(self):
    _file = self.cleaned_data.get('filefield')
    contents = _file.read()

If you do need it on the disk, you know where to go from here :) write it to a temporary location and do some magic on it!

like image 100
Yuji 'Tomita' Tomita Avatar answered Sep 28 '22 07:09

Yuji 'Tomita' Tomita