files.txt 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. ==============
  2. Managing files
  3. ==============
  4. This document describes Django's file access APIs for files such as those
  5. uploaded by a user. The lower level APIs are general enough that you could use
  6. them for other purposes. If you want to handle "static files" (JS, CSS, etc.),
  7. see :doc:`/howto/static-files/index`.
  8. By default, Django stores files locally, using the :setting:`MEDIA_ROOT` and
  9. :setting:`MEDIA_URL` settings. The examples below assume that you're using these
  10. defaults.
  11. However, Django provides ways to write custom `file storage systems`_ that
  12. allow you to completely customize where and how Django stores files. The
  13. second half of this document describes how these storage systems work.
  14. .. _file storage systems: `File storage`_
  15. Using files in models
  16. =====================
  17. When you use a :class:`~django.db.models.FileField` or
  18. :class:`~django.db.models.ImageField`, Django provides a set of APIs you can use
  19. to deal with that file.
  20. Consider the following model, using an :class:`~django.db.models.ImageField` to
  21. store a photo::
  22. from django.db import models
  23. class Car(models.Model):
  24. name = models.CharField(max_length=255)
  25. price = models.DecimalField(max_digits=5, decimal_places=2)
  26. photo = models.ImageField(upload_to="cars")
  27. specs = models.FileField(upload_to="specs")
  28. Any ``Car`` instance will have a ``photo`` attribute that you can use to get at
  29. the details of the attached photo:
  30. .. code-block:: pycon
  31. >>> car = Car.objects.get(name="57 Chevy")
  32. >>> car.photo
  33. <ImageFieldFile: cars/chevy.jpg>
  34. >>> car.photo.name
  35. 'cars/chevy.jpg'
  36. >>> car.photo.path
  37. '/media/cars/chevy.jpg'
  38. >>> car.photo.url
  39. 'https://media.example.com/cars/chevy.jpg'
  40. This object -- ``car.photo`` in the example -- is a ``File`` object, which means
  41. it has all the methods and attributes described below.
  42. .. note::
  43. The file is saved as part of saving the model in the database, so the actual
  44. file name used on disk cannot be relied on until after the model has been
  45. saved.
  46. For example, you can change the file name by setting the file's
  47. :attr:`~django.core.files.File.name` to a path relative to the file storage's
  48. location (:setting:`MEDIA_ROOT` if you are using the default
  49. :class:`~django.core.files.storage.FileSystemStorage`):
  50. .. code-block:: pycon
  51. >>> import os
  52. >>> from django.conf import settings
  53. >>> initial_path = car.photo.path
  54. >>> car.photo.name = "cars/chevy_ii.jpg"
  55. >>> new_path = settings.MEDIA_ROOT + car.photo.name
  56. >>> # Move the file on the filesystem
  57. >>> os.rename(initial_path, new_path)
  58. >>> car.save()
  59. >>> car.photo.path
  60. '/media/cars/chevy_ii.jpg'
  61. >>> car.photo.path == new_path
  62. True
  63. To save an existing file on disk to a :class:`~django.db.models.FileField`:
  64. .. code-block:: pycon
  65. >>> from pathlib import Path
  66. >>> from django.core.files import File
  67. >>> path = Path("/some/external/specs.pdf")
  68. >>> car = Car.objects.get(name="57 Chevy")
  69. >>> with path.open(mode="rb") as f:
  70. ... car.specs = File(f, name=path.name)
  71. ... car.save()
  72. ...
  73. .. note::
  74. While :class:`~django.db.models.ImageField` non-image data attributes, such
  75. as ``height``, ``width``, and ``size`` are available on the instance, the
  76. underlying image data cannot be used without reopening the image. For
  77. example:
  78. .. code-block:: pycon
  79. >>> from PIL import Image
  80. >>> car = Car.objects.get(name="57 Chevy")
  81. >>> car.photo.width
  82. 191
  83. >>> car.photo.height
  84. 287
  85. >>> image = Image.open(car.photo)
  86. # Raises ValueError: seek of closed file.
  87. >>> car.photo.open()
  88. <ImageFieldFile: cars/chevy.jpg>
  89. >>> image = Image.open(car.photo)
  90. >>> image
  91. <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=191x287 at 0x7F99A94E9048>
  92. The ``File`` object
  93. ===================
  94. Internally, Django uses a :class:`django.core.files.File` instance any time it
  95. needs to represent a file.
  96. Most of the time you'll use a ``File`` that Django's given you (i.e. a file
  97. attached to a model as above, or perhaps an uploaded file).
  98. If you need to construct a ``File`` yourself, the easiest way is to create one
  99. using a Python built-in ``file`` object:
  100. .. code-block:: pycon
  101. >>> from django.core.files import File
  102. # Create a Python file object using open()
  103. >>> f = open("/path/to/hello.world", "w")
  104. >>> myfile = File(f)
  105. Now you can use any of the documented attributes and methods
  106. of the :class:`~django.core.files.File` class.
  107. Be aware that files created in this way are not automatically closed.
  108. The following approach may be used to close files automatically:
  109. .. code-block:: pycon
  110. >>> from django.core.files import File
  111. # Create a Python file object using open() and the with statement
  112. >>> with open("/path/to/hello.world", "w") as f:
  113. ... myfile = File(f)
  114. ... myfile.write("Hello World")
  115. ...
  116. >>> myfile.closed
  117. True
  118. >>> f.closed
  119. True
  120. Closing files is especially important when accessing file fields in a loop
  121. over a large number of objects. If files are not manually closed after
  122. accessing them, the risk of running out of file descriptors may arise. This
  123. may lead to the following error:
  124. .. code-block:: pytb
  125. OSError: [Errno 24] Too many open files
  126. File storage
  127. ============
  128. Behind the scenes, Django delegates decisions about how and where to store files
  129. to a file storage system. This is the object that actually understands things
  130. like file systems, opening and reading files, etc.
  131. Django's default file storage is
  132. ``'``:class:`django.core.files.storage.FileSystemStorage`\ ``'``. If you don't
  133. explicitly provide a storage system in the ``default`` key of the
  134. :setting:`STORAGES` setting, this is the one that will be used.
  135. See below for details of the built-in default file storage system, and see
  136. :doc:`/howto/custom-file-storage` for information on writing your own file
  137. storage system.
  138. Storage objects
  139. ---------------
  140. Though most of the time you'll want to use a ``File`` object (which delegates to
  141. the proper storage for that file), you can use file storage systems directly.
  142. You can create an instance of some custom file storage class, or -- often more
  143. useful -- you can use the global default storage system:
  144. .. code-block:: pycon
  145. >>> from django.core.files.base import ContentFile
  146. >>> from django.core.files.storage import default_storage
  147. >>> path = default_storage.save("path/to/file", ContentFile(b"new content"))
  148. >>> path
  149. 'path/to/file'
  150. >>> default_storage.size(path)
  151. 11
  152. >>> default_storage.open(path).read()
  153. b'new content'
  154. >>> default_storage.delete(path)
  155. >>> default_storage.exists(path)
  156. False
  157. See :doc:`/ref/files/storage` for the file storage API.
  158. .. _builtin-fs-storage:
  159. The built-in filesystem storage class
  160. -------------------------------------
  161. Django ships with a :class:`django.core.files.storage.FileSystemStorage` class
  162. which implements basic local filesystem file storage.
  163. For example, the following code will store uploaded files under
  164. ``/media/photos`` regardless of what your :setting:`MEDIA_ROOT` setting is::
  165. from django.core.files.storage import FileSystemStorage
  166. from django.db import models
  167. fs = FileSystemStorage(location="/media/photos")
  168. class Car(models.Model):
  169. ...
  170. photo = models.ImageField(storage=fs)
  171. :doc:`Custom storage systems </howto/custom-file-storage>` work the same way:
  172. you can pass them in as the ``storage`` argument to a
  173. :class:`~django.db.models.FileField`.
  174. Using a callable
  175. ----------------
  176. You can use a callable as the :attr:`~django.db.models.FileField.storage`
  177. parameter for :class:`~django.db.models.FileField` or
  178. :class:`~django.db.models.ImageField`. This allows you to modify the used
  179. storage at runtime, selecting different storages for different environments,
  180. for example.
  181. Your callable will be evaluated when your models classes are loaded, and must
  182. return an instance of :class:`~django.core.files.storage.Storage`.
  183. For example::
  184. from django.conf import settings
  185. from django.db import models
  186. from .storages import MyLocalStorage, MyRemoteStorage
  187. def select_storage():
  188. return MyLocalStorage() if settings.DEBUG else MyRemoteStorage()
  189. class MyModel(models.Model):
  190. my_file = models.FileField(storage=select_storage)
  191. In order to set a storage defined in the :setting:`STORAGES` setting you can
  192. use :data:`~django.core.files.storage.storages`::
  193. from django.core.files.storage import storages
  194. def select_storage():
  195. return storages["mystorage"]
  196. class MyModel(models.Model):
  197. upload = models.FileField(storage=select_storage)