files.txt 8.4 KB

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