files.txt 6.3 KB

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