- March 11, 2007
- Pre .96
- newforms files zip-files upload
- 3 (after 3 ratings)
I altered the ZipUploadForm by removing lines 33 - 34:
if 'zip_file' in self.clean_data: zip_file = self.clean_data['zip_file']
and adding a return statement to clean_zipfile, which returns the validated zip file. I also added the line:
zip_file.clean = clean_zipfile
so that when the full_clean() in called on the form, clean_zipfile will automatically run.
All other code (the view & template) remain the same.
Disclaimer I'm not that familiar with newforms, so please forgive me if some the explanation as to why this works is incorrect ;) Who knows, maybe the first guy had it right.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
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()
More like this
- FieldsetForm by Ciantic 8 years, 1 month ago
- improved getattr template filter by luckystarr 7 years, 8 months ago
- Unzip a .zip file uploaded with FileBrowser by shacker 5 years, 4 months ago
- AlphabeticFilterSpec by marinho 7 years ago
- Model inheritance with content type and inheritance-aware manager by dan90 6 years, 8 months ago