files.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. import datetime
  2. import os
  3. from django import forms
  4. from django.db.models.fields import Field
  5. from django.core import checks
  6. from django.core.exceptions import ImproperlyConfigured
  7. from django.core.files.base import File
  8. from django.core.files.storage import default_storage
  9. from django.core.files.images import ImageFile
  10. from django.db.models import signals
  11. from django.utils.encoding import force_str, force_text
  12. from django.utils import six
  13. from django.utils.translation import ugettext_lazy as _
  14. class FieldFile(File):
  15. def __init__(self, instance, field, name):
  16. super(FieldFile, self).__init__(None, name)
  17. self.instance = instance
  18. self.field = field
  19. self.storage = field.storage
  20. self._committed = True
  21. def __eq__(self, other):
  22. # Older code may be expecting FileField values to be simple strings.
  23. # By overriding the == operator, it can remain backwards compatibility.
  24. if hasattr(other, 'name'):
  25. return self.name == other.name
  26. return self.name == other
  27. def __ne__(self, other):
  28. return not self.__eq__(other)
  29. def __hash__(self):
  30. return hash(self.name)
  31. # The standard File contains most of the necessary properties, but
  32. # FieldFiles can be instantiated without a name, so that needs to
  33. # be checked for here.
  34. def _require_file(self):
  35. if not self:
  36. raise ValueError("The '%s' attribute has no file associated with it." % self.field.name)
  37. def _get_file(self):
  38. self._require_file()
  39. if not hasattr(self, '_file') or self._file is None:
  40. self._file = self.storage.open(self.name, 'rb')
  41. return self._file
  42. def _set_file(self, file):
  43. self._file = file
  44. def _del_file(self):
  45. del self._file
  46. file = property(_get_file, _set_file, _del_file)
  47. def _get_path(self):
  48. self._require_file()
  49. return self.storage.path(self.name)
  50. path = property(_get_path)
  51. def _get_url(self):
  52. self._require_file()
  53. return self.storage.url(self.name)
  54. url = property(_get_url)
  55. def _get_size(self):
  56. self._require_file()
  57. if not self._committed:
  58. return self.file.size
  59. return self.storage.size(self.name)
  60. size = property(_get_size)
  61. def open(self, mode='rb'):
  62. self._require_file()
  63. self.file.open(mode)
  64. # open() doesn't alter the file's contents, but it does reset the pointer
  65. open.alters_data = True
  66. # In addition to the standard File API, FieldFiles have extra methods
  67. # to further manipulate the underlying file, as well as update the
  68. # associated model instance.
  69. def save(self, name, content, save=True):
  70. name = self.field.generate_filename(self.instance, name)
  71. self.name = self.storage.save(name, content)
  72. setattr(self.instance, self.field.name, self.name)
  73. # Update the filesize cache
  74. self._size = content.size
  75. self._committed = True
  76. # Save the object because it has changed, unless save is False
  77. if save:
  78. self.instance.save()
  79. save.alters_data = True
  80. def delete(self, save=True):
  81. if not self:
  82. return
  83. # Only close the file if it's already open, which we know by the
  84. # presence of self._file
  85. if hasattr(self, '_file'):
  86. self.close()
  87. del self.file
  88. self.storage.delete(self.name)
  89. self.name = None
  90. setattr(self.instance, self.field.name, self.name)
  91. # Delete the filesize cache
  92. if hasattr(self, '_size'):
  93. del self._size
  94. self._committed = False
  95. if save:
  96. self.instance.save()
  97. delete.alters_data = True
  98. def _get_closed(self):
  99. file = getattr(self, '_file', None)
  100. return file is None or file.closed
  101. closed = property(_get_closed)
  102. def close(self):
  103. file = getattr(self, '_file', None)
  104. if file is not None:
  105. file.close()
  106. def __getstate__(self):
  107. # FieldFile needs access to its associated model field and an instance
  108. # it's attached to in order to work properly, but the only necessary
  109. # data to be pickled is the file's name itself. Everything else will
  110. # be restored later, by FileDescriptor below.
  111. return {'name': self.name, 'closed': False, '_committed': True, '_file': None}
  112. class FileDescriptor(object):
  113. """
  114. The descriptor for the file attribute on the model instance. Returns a
  115. FieldFile when accessed so you can do stuff like::
  116. >>> from myapp.models import MyModel
  117. >>> instance = MyModel.objects.get(pk=1)
  118. >>> instance.file.size
  119. Assigns a file object on assignment so you can do::
  120. >>> with open('/tmp/hello.world', 'r') as f:
  121. ... instance.file = File(f)
  122. """
  123. def __init__(self, field):
  124. self.field = field
  125. def __get__(self, instance=None, owner=None):
  126. if instance is None:
  127. raise AttributeError(
  128. "The '%s' attribute can only be accessed from %s instances."
  129. % (self.field.name, owner.__name__))
  130. # This is slightly complicated, so worth an explanation.
  131. # instance.file`needs to ultimately return some instance of `File`,
  132. # probably a subclass. Additionally, this returned object needs to have
  133. # the FieldFile API so that users can easily do things like
  134. # instance.file.path and have that delegated to the file storage engine.
  135. # Easy enough if we're strict about assignment in __set__, but if you
  136. # peek below you can see that we're not. So depending on the current
  137. # value of the field we have to dynamically construct some sort of
  138. # "thing" to return.
  139. # The instance dict contains whatever was originally assigned
  140. # in __set__.
  141. file = instance.__dict__[self.field.name]
  142. # If this value is a string (instance.file = "path/to/file") or None
  143. # then we simply wrap it with the appropriate attribute class according
  144. # to the file field. [This is FieldFile for FileFields and
  145. # ImageFieldFile for ImageFields; it's also conceivable that user
  146. # subclasses might also want to subclass the attribute class]. This
  147. # object understands how to convert a path to a file, and also how to
  148. # handle None.
  149. if isinstance(file, six.string_types) or file is None:
  150. attr = self.field.attr_class(instance, self.field, file)
  151. instance.__dict__[self.field.name] = attr
  152. # Other types of files may be assigned as well, but they need to have
  153. # the FieldFile interface added to the. Thus, we wrap any other type of
  154. # File inside a FieldFile (well, the field's attr_class, which is
  155. # usually FieldFile).
  156. elif isinstance(file, File) and not isinstance(file, FieldFile):
  157. file_copy = self.field.attr_class(instance, self.field, file.name)
  158. file_copy.file = file
  159. file_copy._committed = False
  160. instance.__dict__[self.field.name] = file_copy
  161. # Finally, because of the (some would say boneheaded) way pickle works,
  162. # the underlying FieldFile might not actually itself have an associated
  163. # file. So we need to reset the details of the FieldFile in those cases.
  164. elif isinstance(file, FieldFile) and not hasattr(file, 'field'):
  165. file.instance = instance
  166. file.field = self.field
  167. file.storage = self.field.storage
  168. # That was fun, wasn't it?
  169. return instance.__dict__[self.field.name]
  170. def __set__(self, instance, value):
  171. instance.__dict__[self.field.name] = value
  172. class FileField(Field):
  173. # The class to wrap instance attributes in. Accessing the file object off
  174. # the instance will always return an instance of attr_class.
  175. attr_class = FieldFile
  176. # The descriptor to use for accessing the attribute off of the class.
  177. descriptor_class = FileDescriptor
  178. description = _("File")
  179. def __init__(self, verbose_name=None, name=None, upload_to='', storage=None, **kwargs):
  180. self._primary_key_set_explicitly = 'primary_key' in kwargs
  181. self._unique_set_explicitly = 'unique' in kwargs
  182. self.storage = storage or default_storage
  183. self.upload_to = upload_to
  184. if callable(upload_to):
  185. self.generate_filename = upload_to
  186. kwargs['max_length'] = kwargs.get('max_length', 100)
  187. super(FileField, self).__init__(verbose_name, name, **kwargs)
  188. def check(self, **kwargs):
  189. errors = super(FileField, self).check(**kwargs)
  190. errors.extend(self._check_unique())
  191. errors.extend(self._check_primary_key())
  192. return errors
  193. def _check_unique(self):
  194. if self._unique_set_explicitly:
  195. return [
  196. checks.Error(
  197. "'unique' is not a valid argument for a %s." % self.__class__.__name__,
  198. hint=None,
  199. obj=self,
  200. id='fields.E200',
  201. )
  202. ]
  203. else:
  204. return []
  205. def _check_primary_key(self):
  206. if self._primary_key_set_explicitly:
  207. return [
  208. checks.Error(
  209. "'primary_key' is not a valid argument for a %s." % self.__class__.__name__,
  210. hint=None,
  211. obj=self,
  212. id='fields.E201',
  213. )
  214. ]
  215. else:
  216. return []
  217. def deconstruct(self):
  218. name, path, args, kwargs = super(FileField, self).deconstruct()
  219. if kwargs.get("max_length", None) == 100:
  220. del kwargs["max_length"]
  221. kwargs['upload_to'] = self.upload_to
  222. if self.storage is not default_storage:
  223. kwargs['storage'] = self.storage
  224. return name, path, args, kwargs
  225. def get_internal_type(self):
  226. return "FileField"
  227. def get_prep_lookup(self, lookup_type, value):
  228. if hasattr(value, 'name'):
  229. value = value.name
  230. return super(FileField, self).get_prep_lookup(lookup_type, value)
  231. def get_prep_value(self, value):
  232. "Returns field's value prepared for saving into a database."
  233. value = super(FileField, self).get_prep_value(value)
  234. # Need to convert File objects provided via a form to unicode for database insertion
  235. if value is None:
  236. return None
  237. return six.text_type(value)
  238. def pre_save(self, model_instance, add):
  239. "Returns field's value just before saving."
  240. file = super(FileField, self).pre_save(model_instance, add)
  241. if file and not file._committed:
  242. # Commit the file to storage prior to saving the model
  243. file.save(file.name, file, save=False)
  244. return file
  245. def contribute_to_class(self, cls, name):
  246. super(FileField, self).contribute_to_class(cls, name)
  247. setattr(cls, self.name, self.descriptor_class(self))
  248. def get_directory_name(self):
  249. return os.path.normpath(force_text(datetime.datetime.now().strftime(force_str(self.upload_to))))
  250. def get_filename(self, filename):
  251. return os.path.normpath(self.storage.get_valid_name(os.path.basename(filename)))
  252. def generate_filename(self, instance, filename):
  253. return os.path.join(self.get_directory_name(), self.get_filename(filename))
  254. def save_form_data(self, instance, data):
  255. # Important: None means "no change", other false value means "clear"
  256. # This subtle distinction (rather than a more explicit marker) is
  257. # needed because we need to consume values that are also sane for a
  258. # regular (non Model-) Form to find in its cleaned_data dictionary.
  259. if data is not None:
  260. # This value will be converted to unicode and stored in the
  261. # database, so leaving False as-is is not acceptable.
  262. if not data:
  263. data = ''
  264. setattr(instance, self.name, data)
  265. def formfield(self, **kwargs):
  266. defaults = {'form_class': forms.FileField, 'max_length': self.max_length}
  267. # If a file has been provided previously, then the form doesn't require
  268. # that a new file is provided this time.
  269. # The code to mark the form field as not required is used by
  270. # form_for_instance, but can probably be removed once form_for_instance
  271. # is gone. ModelForm uses a different method to check for an existing file.
  272. if 'initial' in kwargs:
  273. defaults['required'] = False
  274. defaults.update(kwargs)
  275. return super(FileField, self).formfield(**defaults)
  276. class ImageFileDescriptor(FileDescriptor):
  277. """
  278. Just like the FileDescriptor, but for ImageFields. The only difference is
  279. assigning the width/height to the width_field/height_field, if appropriate.
  280. """
  281. def __set__(self, instance, value):
  282. previous_file = instance.__dict__.get(self.field.name)
  283. super(ImageFileDescriptor, self).__set__(instance, value)
  284. # To prevent recalculating image dimensions when we are instantiating
  285. # an object from the database (bug #11084), only update dimensions if
  286. # the field had a value before this assignment. Since the default
  287. # value for FileField subclasses is an instance of field.attr_class,
  288. # previous_file will only be None when we are called from
  289. # Model.__init__(). The ImageField.update_dimension_fields method
  290. # hooked up to the post_init signal handles the Model.__init__() cases.
  291. # Assignment happening outside of Model.__init__() will trigger the
  292. # update right here.
  293. if previous_file is not None:
  294. self.field.update_dimension_fields(instance, force=True)
  295. class ImageFieldFile(ImageFile, FieldFile):
  296. def delete(self, save=True):
  297. # Clear the image dimensions cache
  298. if hasattr(self, '_dimensions_cache'):
  299. del self._dimensions_cache
  300. super(ImageFieldFile, self).delete(save)
  301. class ImageField(FileField):
  302. attr_class = ImageFieldFile
  303. descriptor_class = ImageFileDescriptor
  304. description = _("Image")
  305. def __init__(self, verbose_name=None, name=None, width_field=None,
  306. height_field=None, **kwargs):
  307. self.width_field, self.height_field = width_field, height_field
  308. super(ImageField, self).__init__(verbose_name, name, **kwargs)
  309. def check(self, **kwargs):
  310. errors = super(ImageField, self).check(**kwargs)
  311. errors.extend(self._check_image_library_installed())
  312. return errors
  313. def _check_image_library_installed(self):
  314. try:
  315. from django.utils.image import Image # NOQA
  316. except ImproperlyConfigured:
  317. return [
  318. checks.Error(
  319. 'Cannot use ImageField because Pillow is not installed.',
  320. hint=('Get Pillow at https://pypi.python.org/pypi/Pillow '
  321. 'or run command "pip install pillow".'),
  322. obj=self,
  323. id='fields.E210',
  324. )
  325. ]
  326. else:
  327. return []
  328. def deconstruct(self):
  329. name, path, args, kwargs = super(ImageField, self).deconstruct()
  330. if self.width_field:
  331. kwargs['width_field'] = self.width_field
  332. if self.height_field:
  333. kwargs['height_field'] = self.height_field
  334. return name, path, args, kwargs
  335. def contribute_to_class(self, cls, name):
  336. super(ImageField, self).contribute_to_class(cls, name)
  337. # Attach update_dimension_fields so that dimension fields declared
  338. # after their corresponding image field don't stay cleared by
  339. # Model.__init__, see bug #11196.
  340. # Only run post-initialization dimension update on non-abstract models
  341. if not cls._meta.abstract:
  342. signals.post_init.connect(self.update_dimension_fields, sender=cls)
  343. def update_dimension_fields(self, instance, force=False, *args, **kwargs):
  344. """
  345. Updates field's width and height fields, if defined.
  346. This method is hooked up to model's post_init signal to update
  347. dimensions after instantiating a model instance. However, dimensions
  348. won't be updated if the dimensions fields are already populated. This
  349. avoids unnecessary recalculation when loading an object from the
  350. database.
  351. Dimensions can be forced to update with force=True, which is how
  352. ImageFileDescriptor.__set__ calls this method.
  353. """
  354. # Nothing to update if the field doesn't have dimension fields.
  355. has_dimension_fields = self.width_field or self.height_field
  356. if not has_dimension_fields:
  357. return
  358. # getattr will call the ImageFileDescriptor's __get__ method, which
  359. # coerces the assigned value into an instance of self.attr_class
  360. # (ImageFieldFile in this case).
  361. file = getattr(instance, self.attname)
  362. # Nothing to update if we have no file and not being forced to update.
  363. if not file and not force:
  364. return
  365. dimension_fields_filled = not(
  366. (self.width_field and not getattr(instance, self.width_field))
  367. or (self.height_field and not getattr(instance, self.height_field))
  368. )
  369. # When both dimension fields have values, we are most likely loading
  370. # data from the database or updating an image field that already had
  371. # an image stored. In the first case, we don't want to update the
  372. # dimension fields because we are already getting their values from the
  373. # database. In the second case, we do want to update the dimensions
  374. # fields and will skip this return because force will be True since we
  375. # were called from ImageFileDescriptor.__set__.
  376. if dimension_fields_filled and not force:
  377. return
  378. # file should be an instance of ImageFieldFile or should be None.
  379. if file:
  380. width = file.width
  381. height = file.height
  382. else:
  383. # No file, so clear dimensions fields.
  384. width = None
  385. height = None
  386. # Update the width and height fields.
  387. if self.width_field:
  388. setattr(instance, self.width_field, width)
  389. if self.height_field:
  390. setattr(instance, self.height_field, height)
  391. def formfield(self, **kwargs):
  392. defaults = {'form_class': forms.ImageField}
  393. defaults.update(kwargs)
  394. return super(ImageField, self).formfield(**defaults)