from cStringIO import StringIO import zipfile from django import newforms as forms from zippers.upload.models import QueuedImageSet # The model that uses the zipfile (has a FileField called 'zip_file') class ZipUploadForm(forms.Form): zip_file = forms.Field( widget=forms.FileInput() ) owner = forms.CharField( max_length=88 ) def clean_zipfile(zip_file): if zip_file.get('content-type') != 'application/zip': msg = 'File upload must be a valid ZIP archive.' raise forms.ValidationError( msg ) else: try: zip = zipfile.ZipFile( StringIO( zip_file['content'] ) ) except: raise forms.ValidationError( "Could not unzip file." ) bad_file = zip.testzip() zip.close() del zip if bad_file: raise forms.ValidationError( msg ) return zip_file # Return the clean zip_file # The line below hooks the function above into the base form. # When the form calls full_clean() it will automatically clean the # zip_file field and add it to the form's clean_data dictionary. zip_file.clean = clean_zipfile def save(self): owner = self.clean_data['owner'] # Get the cleaned zip_file stuff filename = self.clean_data['zip_file']['filename'] zipdata = self.clean_data['zip_file']['content'] q = QueuedImageSet(file_owner=owner) q.save_zip_file_file(filename, zipdata) q.save()