Upload a zip file with newforms

 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

  1. FieldsetForm by Ciantic 7 years ago
  2. improved getattr template filter by luckystarr 6 years, 7 months ago
  3. Unzip a .zip file uploaded with FileBrowser by shacker 4 years, 2 months ago
  4. AlphabeticFilterSpec by marinho 5 years, 11 months ago
  5. Model inheritance with content type and inheritance-aware manager by dan90 5 years, 7 months ago

Comments

vdemeester (on March 12, 2007):

Hi there,

If you don't want to write "zip_file.clean = clean_zipfile", you just have to rename clean_zipfile by clean_zip_file.

newforms seems to called all clean_FIELDNAME when full_clean() called..

But your way of doing is also a good way :p

#

kylefox (on March 12, 2007):

Thanks, wasn't sure about that. You know, I wondered if the original author had intended to name the function & field the same because I had a slight feeling django would do that!

#

Pistahh (on June 21, 2007):

Bug: The variable "msg" is uninitialized in line 25. (It is only initialized in line 14 but it is the "then" branch of the if statement, while line 25 is the "else" branch.

#

(Forgotten your password?)