Ticket #7614: third_patch.diff
File third_patch.diff, 10.8 KB (added by , 16 years ago) |
---|
-
django/db/models/fields/__init__.py
766 766 def get_db_prep_save(self, value): 767 767 "Returns field's value prepared for saving into a database." 768 768 # Need to convert UploadedFile objects provided via a form to unicode for database insertion 769 if value is None: 769 if hasattr(value, 'file_name'): 770 return value.file_name 771 elif value is None: 770 772 return None 771 return unicode(value) 773 else: 774 return unicode(value) 772 775 773 776 def get_manipulator_fields(self, opts, manipulator, change, name_prefix='', rel=False, follow=True): 774 777 field_list = Field.get_manipulator_fields(self, opts, manipulator, change, name_prefix, rel, follow) … … 857 860 return os.path.normpath(f) 858 861 859 862 def save_form_data(self, instance, data): 860 from django. newforms.fieldsimport UploadedFile863 from django.core.files.uploadedfile import UploadedFile 861 864 if data and isinstance(data, UploadedFile): 862 getattr(instance, "save_%s_file" % self.name)(data.file name, data.data, save=False)865 getattr(instance, "save_%s_file" % self.name)(data.file_name, data, save=False) 863 866 864 867 def formfield(self, **kwargs): 865 868 defaults = {'form_class': forms.FileField} -
django/core/files/uploadedfile.py
3 3 """ 4 4 5 5 import os 6 import warnings 6 7 try: 7 8 from cStringIO import StringIO 8 9 except ImportError: … … 21 22 DEFAULT_CHUNK_SIZE = 64 * 2**10 22 23 23 24 def __init__(self, file_name=None, content_type=None, file_size=None, charset=None): 24 self. file_name = file_name25 self.name = file_name 25 26 self.file_size = file_size 26 27 self.content_type = content_type 27 28 self.charset = charset 28 29 29 30 def __repr__(self): 30 return "<%s: %s (%s)>" % (self.__class__.__name__, self. file_name, self.content_type)31 return "<%s: %s (%s)>" % (self.__class__.__name__, self.name, self.content_type) 31 32 32 def _set_ file_name(self, name):33 def _set_name(self, name): 33 34 # Sanitize the file name so that it can't be dangerous. 34 35 if name is not None: 35 36 # Just use the basename of the file -- anything else is dangerous. 36 37 name = os.path.basename(name) 37 38 38 39 # File names longer than 255 characters can cause problems on older OSes. 39 40 if len(name) > 255: 40 41 name, ext = os.path.splitext(name) 41 42 name = name[:255 - len(ext)] + ext 42 43 self._file_name = name 44 43 44 self._name = name 45 46 def _get_name(self): 47 return self._name 48 49 name = property(_get_name, _set_name) 50 45 51 def _get_file_name(self): 46 return self._file_name 47 48 file_name = property(_get_file_name, _set_file_name) 52 warnings.warn( 53 message = "To access the filename, please use the .name attribute.", 54 category = DeprecationWarning, 55 stacklevel = 1, 56 ) 57 return self.name 49 58 59 def _set_file_name(self, name): 60 warnings.warn( 61 message = "To access the filename, please use the .name attribute.", 62 category = DeprecationWarning, 63 stacklevel = 1, 64 ) 65 self.name = name 66 67 file_name = filename = property(_get_file_name, _set_file_name) 68 69 def _get_data(self): 70 warnings.warn( 71 message = "To access the data, please use the .read() or .chunk() UploadedFile interface.", 72 category = DeprecationWarning, 73 stacklevel = 1, 74 ) 75 return self.read() 76 77 data = property(_get_data) 78 50 79 def chunk(self, chunk_size=None): 51 80 """ 52 81 Read the file and yield chucks of ``chunk_size`` bytes (defaults to … … 76 105 chunk_size = UploadedFile.DEFAULT_CHUNK_SIZE 77 106 return self.file_size < chunk_size 78 107 79 # Abstract methods; subclasses *must* def aultread() and probably should108 # Abstract methods; subclasses *must* define read() and probably should 80 109 # define open/close. 81 110 def read(self, num_bytes=None): 82 111 raise NotImplementedError() … … 96 125 stacklevel = 2 97 126 ) 98 127 backwards_translate = { 99 'filename': ' file_name',128 'filename': 'name', 100 129 'content-type': 'content_type', 101 130 } 102 131 103 132 if key == 'content': 104 133 return self.read() 105 134 elif key == 'filename': 106 return self. file_name135 return self.name 107 136 elif key == 'content-type': 108 137 return self.content_type 109 138 else: … … 168 197 """ 169 198 def __init__(self, name, content, content_type='text/plain'): 170 199 self.file = StringIO(content or '') 171 self. file_name = name200 self.name = name 172 201 self.field_name = None 173 202 self.file_size = len(content or '') 174 203 self.content_type = content_type … … 188 217 file_dict.get('content-type', 'text/plain')) 189 218 190 219 from_dict = classmethod(from_dict) 220 221 def read(self): 222 self.file.seek(0) 223 return super(SimpleUploadedFile, self).read() 224 -
django/newforms/fields.py
27 27 28 28 from util import ErrorList, ValidationError 29 29 from widgets import TextInput, PasswordInput, HiddenInput, MultipleHiddenInput, FileInput, CheckboxInput, Select, NullBooleanSelect, SelectMultiple, DateTimeInput 30 from django.core.files.uploadedfile import SimpleUploadedFile as UploadedFile 30 31 31 32 32 __all__ = ( 33 33 'Field', 'CharField', 'IntegerField', 34 34 'DEFAULT_DATE_INPUT_FORMATS', 'DateField', … … 419 419 # It's OK if Django settings aren't configured. 420 420 URL_VALIDATOR_USER_AGENT = 'Django (http://www.djangoproject.com/)' 421 421 422 class UploadedFile(StrAndUnicode):423 "A wrapper for files uploaded in a FileField"424 def __init__(self, filename, data):425 self.filename = filename426 self.data = data427 422 428 def __unicode__(self):429 """430 The unicode representation is the filename, so that the pre-database-insertion431 logic can use UploadedFile objects432 """433 return self.filename434 435 423 class FileField(Field): 436 424 widget = FileInput 437 425 default_error_messages = { … … 460 448 category = DeprecationWarning, 461 449 stacklevel = 2 462 450 ) 451 data = UploadedFile(data['filename'], data['content']) 463 452 464 453 try: 465 454 file_name = data.file_name 466 455 file_size = data.file_size 467 456 except AttributeError: 468 try: 469 file_name = data.get('filename') 470 file_size = bool(data['content']) 471 except (AttributeError, KeyError): 472 raise ValidationError(self.error_messages['invalid']) 457 raise ValidationError(self.error_messages['invalid']) 473 458 474 459 if not file_name: 475 460 raise ValidationError(self.error_messages['invalid']) 476 461 if not file_size: 477 462 raise ValidationError(self.error_messages['empty']) 478 463 479 return UploadedFile(file_name, data)464 return data 480 465 481 466 class ImageField(FileField): 482 467 default_error_messages = { -
tests/modeltests/model_forms/models.py
803 803 >>> f.is_valid() 804 804 True 805 805 >>> type(f.cleaned_data['file']) 806 <class 'django. newforms.fields.UploadedFile'>806 <class 'django.core.files.uploadedfile.SimpleUploadedFile'> 807 807 >>> instance = f.save() 808 808 >>> instance.file 809 809 u'...test1.txt' … … 814 814 >>> f.is_valid() 815 815 True 816 816 >>> type(f.cleaned_data['file']) 817 <class 'django. newforms.fields.UploadedFile'>817 <class 'django.core.files.uploadedfile.SimpleUploadedFile'> 818 818 >>> instance = f.save() 819 819 >>> instance.file 820 820 u'...test1.txt' … … 906 906 >>> f.is_valid() 907 907 True 908 908 >>> type(f.cleaned_data['image']) 909 <class 'django. newforms.fields.UploadedFile'>909 <class 'django.core.files.uploadedfile.SimpleUploadedFile'> 910 910 >>> instance = f.save() 911 911 >>> instance.image 912 912 u'...test.png' … … 918 918 >>> f.is_valid() 919 919 True 920 920 >>> type(f.cleaned_data['image']) 921 <class 'django. newforms.fields.UploadedFile'>921 <class 'django.core.files.uploadedfile.SimpleUploadedFile'> 922 922 >>> instance = f.save() 923 923 >>> instance.image 924 924 u'...test.png' -
tests/regressiontests/forms/fields.py
800 800 ValidationError: [u'The submitted file is empty.'] 801 801 802 802 >>> type(f.clean(SimpleUploadedFile('name', 'Some File Content'))) 803 <class 'django. newforms.fields.UploadedFile'>803 <class 'django.core.files.uploadedfile.SimpleUploadedFile'> 804 804 805 805 >>> type(f.clean(SimpleUploadedFile('name', 'Some File Content'), 'files/test4.pdf')) 806 <class 'django. newforms.fields.UploadedFile'>806 <class 'django.core.files.uploadedfile.SimpleUploadedFile'> 807 807 808 808 # URLField ################################################################## 809 809 -
docs/newforms.txt
1331 1331 * Validates that non-empty file data has been bound to the form. 1332 1332 * Error message keys: ``required``, ``invalid``, ``missing``, ``empty`` 1333 1333 1334 An ``UploadedFile`` object has two attributes: 1334 To learn more about the ``UploadedFile`` object, see the `file uploads documentation`_. 1335 1335 1336 ====================== ====================================================1337 Attribute Description1338 ====================== ====================================================1339 ``filename`` The name of the file, provided by the uploading1340 client.1341 1342 ``content`` The array of bytes comprising the file content.1343 ====================== ====================================================1344 1345 The string representation of an ``UploadedFile`` is the same as the filename1346 attribute.1347 1348 1336 When you use a ``FileField`` on a form, you must also remember to 1349 1337 `bind the file data to the form`_. 1350 1338 1339 .. _file uploads documentation: ../upload_handling/ 1351 1340 .. _`bind the file data to the form`: `Binding uploaded files to a form`_ 1352 1341 1353 1342 ``FilePathField``