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