django - How to use the ExtFileField snippet? -
as want restrict fileupload types of audiofiles, found django snippet http://djangosnippets.org/snippets/977/, restricting fileupload files within extension whitelist:
class extfilefield(forms.filefield): """ same forms.filefield, can specify file extension whitelist. >>> django.core.files.uploadedfile import simpleuploadedfile >>> >>> t = extfilefield(ext_whitelist=(".pdf", ".txt")) >>> >>> t.clean(simpleuploadedfile('filename.pdf', 'some file content')) >>> t.clean(simpleuploadedfile('filename.txt', 'some file content')) >>> >>> t.clean(simpleuploadedfile('filename.exe', 'some file content')) traceback (most recent call last): ... validationerror: [u'not allowed filetype!'] """ def __init__(self, *args, **kwargs): ext_whitelist = kwargs.pop("ext_whitelist") self.ext_whitelist = [i.lower() in ext_whitelist] super(extfilefield, self).__init__(*args, **kwargs) def clean(self, *args, **kwargs): data = super(extfilefield, self).clean(*args, **kwargs) filename = data.name ext = os.path.splitext(filename)[1] ext = ext.lower() if ext not in self.ext_whitelist: raise forms.validationerror("not allowed filetype!")
in forms have standard filefield until now. uploads file, saves , works well. substitute filefield this
class newitemform(forms.modelform): def __init__(self, *args, **kwargs): super(newitemform, self).__init__(*args, **kwargs) self.fields['file']=extfilefield(ext_whitelist=(".wav", ".aif", ".flac")) class meta: model = item fields = ('file','name','meta1','tags')
when trying upload file not in whitelist error message "not allowed filetype!", good. when uploading file within whitelist error message "this field cannot blank.", not understand. have suspicion has way replaced filefield modelform. right way it?
at end of 'clean' method, make sure return data normal clean method of forms.filefield has access it. in current implementation have (which directly snippet), forms.filefield clean method not uploaded file.
i needed adjust method since had fields not required. result, implementation fail trying access name property of data (since data none).
lastly, can same sort of file whitelisting content types (not shown below), instead of checking extension check data.file.content_type against content_whitelist param pass field constructor (in same fashion ext_whitelist).
def clean(self, *args, **kwargs): data = super(extfilefield, self).clean(*args, **kwargs) if data: filename = data.name ext = os.path.splitext(filename)[1] ext = ext.lower() if ext not in self.ext_whitelist: raise forms.validationerror("filetype '%s' not allowed field" % ext) elif not data , self.required: raise forms.validationerror("required file not found %s" % self.label) return data
Comments
Post a Comment