#14063: Validating form file fields is hard
---------------------------+------------------------------------------------
 Reporter:  olau           |       Owner:  nobody    
   Status:  new            |   Milestone:            
Component:  Uncategorized  |     Version:  1.2       
 Keywords:                 |       Stage:  Unreviewed
Has_patch:  0              |  
---------------------------+------------------------------------------------
 I have an application where I need to validate a file uploaded through a
 form. I'd like to do this with the clean_xxx() method for the field.
 However, I need the file to be present in the file system because the
 validation is using external libraries and applications.

 I don't think that's an unreasonable requirement, but it is not
 straightforward with the current API. After some digging, I thought I
 could use the storage classes, something like
 {{{
 f = self.cleaned_data['myfile']
 storage = FileSystemStorage(location="/tmp")
 path = storage.save(tempfile.mktemp(dir="/tmp"), f)
 try:
     if not validate_file(path):
         raise forms.ValidationError(...)
 finally:
     storage.delete(path)
 }}}

 But this doesn't work with the temporary file backend because it opens and
 closes the file, and as far as I can tell, there's no straight-forward way
 of reopening it again. So currently, I'm doing something like this:

 {{{
 f = self.cleaned_data['myfile']
 if hasattr(f, 'temporary_file_path'):
     path = f.temporary_file_path()
     cleanup = False
 else:
     import tempfile
     path = tempfile.mktemp(dir="/tmp")
     from django.core.files.storage import FileSystemStorage
     storage = FileSystemStorage(location="/tmp")
     path = storage.save(path, f)
     cleanup = True

 try:
     if not validate_file(path):
         raise forms.ValidationError(...)
 finally:
     if cleanup:
         storage.delete(path)
 }}}
 It occurs to me that the API ought to have a more elegant way of doing
 this?

-- 
Ticket URL: <http://code.djangoproject.com/ticket/14063>
Django <http://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

-- 
You received this message because you are subscribed to the Google Groups 
"Django updates" group.
To post to this group, send email to django-upda...@googlegroups.com.
To unsubscribe from this group, send email to 
django-updates+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-updates?hl=en.

Reply via email to