files.txt 6.8 KB

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