Posted By

tclancy on 10/22/10


Tagged


Versions (?)

Django Validated Upload Field


 / Published in: Python
 

URL: http://www.neverfriday.com/sweetfriday/2008/03/validating-file-uploads-with-d.html

Inspired by the linked code.

  1. import os
  2.  
  3. from django import forms
  4. from django.conf import settings
  5.  
  6.  
  7. class ValidatedFileField(forms.FileField):
  8. def __init__(self, file_extensions, content_types,
  9. max_file_size=None, *args, **kwargs):
  10. super(ValidatedFileField, self).__init__(*args, **kwargs)
  11. self.file_extensions = [f.lower().replace('.', '')
  12. for f in file_extensions]
  13. self.content_types = content_types
  14. self.max_file_size = max_file_size
  15.  
  16. def clean(self, data, initial=None):
  17. from django.template.defaultfilters import filesizeformat
  18. if not data and initial:
  19. return initial
  20. f = super(ValidatedFileField, self).clean(data)
  21. if not f:
  22. return f
  23. if self.max_file_size and self.max_file_size < f.size:
  24. raise forms.ValidationError('Files cannot exceed %s in size' %
  25. filesizeformat(self.max_file_size))
  26. # not allowing files without an extension, really a preference thing
  27. if not f.name or f.name.find('.') == -1:
  28. raise forms.ValidationError('Does not appear to be a valid file')
  29. extension = os.path.splitext(f.name)[-1].lower().replace('.', '')
  30. if not extension in self.file_extensions or \
  31. not f.content_type in self.content_types:
  32. raise forms.ValidationError('Accepted file types: %s' %\
  33. ' '.join(self.file_extensions))
  34. return super(ValidatedFileField, self).clean(data)

Report this snippet  

You need to login to post a comment.