files.py 20 KB

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