files.txt 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  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. The ``File`` object
  61. ===================
  62. Internally, Django uses a :class:`django.core.files.File` instance any time it
  63. needs to represent a file.
  64. Most of the time you'll use a ``File`` that Django's given you (i.e. a file
  65. attached to a model as above, or perhaps an uploaded file).
  66. If you need to construct a ``File`` yourself, the easiest way is to create one
  67. using a Python built-in ``file`` object::
  68. >>> from django.core.files import File
  69. # Create a Python file object using open()
  70. >>> f = open('/path/to/hello.world', 'w')
  71. >>> myfile = File(f)
  72. Now you can use any of the documented attributes and methods
  73. of the :class:`~django.core.files.File` class.
  74. Be aware that files created in this way are not automatically closed.
  75. The following approach may be used to close files automatically::
  76. >>> from django.core.files import File
  77. # Create a Python file object using open() and the with statement
  78. >>> with open('/path/to/hello.world', 'w') as f:
  79. ... myfile = File(f)
  80. ... myfile.write('Hello World')
  81. ...
  82. >>> myfile.closed
  83. True
  84. >>> f.closed
  85. True
  86. Closing files is especially important when accessing file fields in a loop
  87. over a large number of objects. If files are not manually closed after
  88. accessing them, the risk of running out of file descriptors may arise. This
  89. may lead to the following error::
  90. OSError: [Errno 24] Too many open files
  91. File storage
  92. ============
  93. Behind the scenes, Django delegates decisions about how and where to store files
  94. to a file storage system. This is the object that actually understands things
  95. like file systems, opening and reading files, etc.
  96. Django's default file storage is given by the :setting:`DEFAULT_FILE_STORAGE`
  97. setting; if you don't explicitly provide a storage system, this is the one that
  98. will be used.
  99. See below for details of the built-in default file storage system, and see
  100. :doc:`/howto/custom-file-storage` for information on writing your own file
  101. storage system.
  102. Storage objects
  103. ---------------
  104. Though most of the time you'll want to use a ``File`` object (which delegates to
  105. the proper storage for that file), you can use file storage systems directly.
  106. You can create an instance of some custom file storage class, or -- often more
  107. useful -- you can use the global default storage system::
  108. >>> from django.core.files.base import ContentFile
  109. >>> from django.core.files.storage import default_storage
  110. >>> path = default_storage.save('path/to/file', ContentFile(b'new content'))
  111. >>> path
  112. 'path/to/file'
  113. >>> default_storage.size(path)
  114. 11
  115. >>> default_storage.open(path).read()
  116. b'new content'
  117. >>> default_storage.delete(path)
  118. >>> default_storage.exists(path)
  119. False
  120. See :doc:`/ref/files/storage` for the file storage API.
  121. .. _builtin-fs-storage:
  122. The built-in filesystem storage class
  123. -------------------------------------
  124. Django ships with a :class:`django.core.files.storage.FileSystemStorage` class
  125. which implements basic local filesystem file storage.
  126. For example, the following code will store uploaded files under
  127. ``/media/photos`` regardless of what your :setting:`MEDIA_ROOT` setting is::
  128. from django.core.files.storage import FileSystemStorage
  129. from django.db import models
  130. fs = FileSystemStorage(location='/media/photos')
  131. class Car(models.Model):
  132. ...
  133. photo = models.ImageField(storage=fs)
  134. :doc:`Custom storage systems </howto/custom-file-storage>` work the same way:
  135. you can pass them in as the ``storage`` argument to a
  136. :class:`~django.db.models.FileField`.